Binding CommandParameter to ItemControl Tap Event

I am using ItemControl and I want to determine which item was selected in the Tap command. My xaml is listed here:

<ItemsControl ItemsSource="{Binding AllMyItems}"> <i:Interaction.Triggers> <i:EventTrigger EventName="Tap"> <cmd:EventToCommand Command="{Binding ItemSelectedCommand}" CommandParameter="{Binding}"/> </i:EventTrigger> </i:Interaction.Triggers> .... item template .... 

and here is my model:

 public RelayCommand<MyItem> ItemSelectedCommand { get; private set; } public MainViewModel() { ItemSelectedCommand = new RelayCommand<MyItem>(ItemSelected); } private void ItemSelected(MyItem myItem) { throw new NotImplementedException(); } 

The event for the command works, but when I get to the ItemSelected method, myItem is either Null or I get an exception that distinguishes it (depending on how I define the CommandParameter in xaml).

I can do this if I use a ListBox and set CommandParameter="{Binding SelectedItem, ElementName=MyItemsList"}

Any ideas on how to do this using ItemsControl? Or does the difference in performance not make a significant difference between the two in Mango?

+4
source share
1 answer

Your Tap event happens in the ItemsControl, you have to put your EventToCommand inside the ItemTemplate, some XAML, to clear everything for you.

 <ItemsControl ItemsSource="{Binding AllMyItems}"> <ItemsControl.ItemTemplate> <...> <i:Interaction.Triggers> <i:EventTrigger EventName="Tap"> <cmd:EventToCommand Command="{Binding ItemSelectedCommand}" CommandParameter="{Binding}"/> </i:EventTrigger> </i:Interaction.Triggers> </...> </ItemsControl.ItemTemplate> ... 
+2
source

Source: https://habr.com/ru/post/1415472/


All Articles