Binding CommandParameter on ItemsControl Tap event

瘦欲@ 提交于 2019-12-07 11:26:13

问题


I'm using an ItemsControl, and I want to identify which item was selected on the Tap command. My xaml is defined 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 view 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 to command works, but when I get to the ItemSelected method, myItem is either Null, or I get an exception casting it (depending on how I define the CommandParameter in the xaml).

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

Any ideas on how to do this with ItemsControl? Or does the perf difference not make much of a difference between the two in Mango?


回答1:


Your Tap Event is occuring on the ItemsControl , you should place your EventToCommand inside the ItemTemplate , some XAML to clear the things 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>
...


来源:https://stackoverflow.com/questions/10841642/binding-commandparameter-on-itemscontrol-tap-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!