在ItemsControl Tap事件上绑定CommandParameter [英] Binding CommandParameter on ItemsControl Tap event
问题描述
我正在使用ItemsControl,并且我想确定在Tap命令上选择了哪个项目.我的xaml在这里定义:
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 ....
这是我的视图模型:
public RelayCommand<MyItem> ItemSelectedCommand { get; private set; }
public MainViewModel()
{
ItemSelectedCommand = new RelayCommand<MyItem>(ItemSelected);
}
private void ItemSelected(MyItem myItem)
{
throw new NotImplementedException();
}
命令事件有效,但是当我进入ItemSelected方法时,myItem要么为Null,要么会抛出异常(取决于我在xaml中定义CommandParameter的方式).
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).
如果我使用ListBox并设置CommandParameter="{Binding SelectedItem, ElementName=MyItemsList"}
I can do this if I use a ListBox and set CommandParameter="{Binding SelectedItem, ElementName=MyItemsList"}
关于如何使用ItemsControl做到这一点的任何想法?还是在芒果方面两者之间的性能差异没有太大差别?
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?
推荐答案
您的Tap事件发生在ItemsControl上,您应该将EventToCommand放在ItemTemplate中,并使用一些XAML来为您清除内容
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>
...
这篇关于在ItemsControl Tap事件上绑定CommandParameter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!