WPF ItemsControl - command on ViewModel does not start from ItemsControl

I am using MV-VM and have a command in my ViewModel called EntitySelectedCommand.

I am trying to get all the items in an ItemsControl to run this command, however it does not work.

I think because each datacontext element is a separate object to which the element is bound, and not the ViewModel?

Can someone point me in the right direction?

Greetings

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> 
+6
data-binding wpf mvvm itemscontrol
source share
2 answers

Your suspicion is true. You have several options:

  • EntitySelectedCommand from your child view model (i.e., each Supplier will also have this property).
  • Change the binding to use a RelativeSource to access and use the DataContext parent ItemsControl .
+13
source share

Take a look at the MVVM Toolkit ... This idea has a refrence command that 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 you can use

 ...Command="{StaticResource EntitySelectedCommandRef}" ... 
+2
source share