views:

312

answers:

2

Hi,

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>
+7  A: 

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.

HTH, Kent

Kent Boogaart
Excellent, many thanks - got it working with RelativeSource as you suggested ...EntitySelected="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}, Path=DataContext.EntitySelectedCommand}"
Andy Clarke
+2  A: 

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}" ...
rudigrobler