Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ItemsControl - Command on ViewModel not firing from within ItemsControl

I'm using M-V-VM and have a command on my ViewModel called 'EntitySelectedCommand'.

I've trying to get all the Items in an ItemsControl to fire this command, however it's not working.

I think it's because each items 'datacontext' is the individual object the item is bound to, rather than the ViewModel?

Can anyone point me in the right direction please?

Cheers,

Andy

<ItemsControl  ItemsSource="{Binding Path=LinkedSuppliers}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <Controls:EntityLabel Grid.Column="0" Grid.Row="0" Content="{Binding Name}" CurrentEntity="{Binding }" EntitySelected="{Binding EntitySelectedCommand}" ></Controls:EntityLabel>                
            <StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
like image 606
Andy Clarke Avatar asked Sep 11 '09 10:09

Andy Clarke


2 Answers

Your suspicion is correct. You have a couple of options:

  1. Expose an EntitySelectedCommand from your child view model as well (ie. each Supplier would have this property, too).
  2. Change your binding to use a RelativeSource to reach out and use the DataContext of the parent ItemsControl.
like image 188
Kent Boogaart Avatar answered Sep 20 '22 10:09

Kent Boogaart


Have a look at the MVVM Toolkit... It has this idea of a command refrence which you can use!

Create a CommandRefrece as a resource and then just use the StaticResource markup extension...

<c:CommandRefrence x:Key="EntitySelectedCommandRef" Command="{Binding EntitySelectedCommand}" />

and then later you can use

...Command="{StaticResource EntitySelectedCommandRef}" ...
like image 36
rudigrobler Avatar answered Sep 22 '22 10:09

rudigrobler