我有一个列表控件和一个ViewModel。如果引发了tapped事件,我会尝试将selectedItems传递给View Model。
我可以编译这段代码:
查看:
<ListView ItemsSource="{Binding AllMedicines}"
SelectionMode="Multiple"
Name="MedicineList" >
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Tapped">
<core:InvokeCommandAction Command="{Binding SelectionChangedCommand}"
CommandParameter="{Binding SelectedItems, ElementName=MedicineList}"/>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</ListView>
ViewModel命令:
SelectionChangedCommand = new RelayCommand<IList>(
items => {
SelectedMedicines = (List<Medicine>) items;
});
但是,如果我点击列表中的某个项目,我会收到此错误消息
System.InvalidCastException: Unable to cast object of type 'Windows.UI.Xaml.Input.TappedRoutedEventArgs' to type 'System.Collections.IList'
我做错了什么?
感谢您的帮助!
答案 0 :(得分:0)
你可以编写一个转换器并对SelectionChanged事件作出反应(或者当你点击它时点击,但是因为SelectedItems是你想要的,你可能想要考虑一下)。
所以你要这样设置:
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="SelectionChanged">
<core:InvokeCommandAction Command="{Binding SelectionChangedCommand}"
InputConverterParameter="{Binding ElementName=MedicineList}"
InputConverter="{StaticResource SelectionChangedConverter}"/>
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
转换器只需要使用ListView并将SelectedItems传递给您的命令:
public class SelectionChangedConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var listView = parameter as ListView;
return listView.SelectedItems;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
当然,转换器需要在某处定义为静态资源:
<local:SelectionChangedConverter x:Key="SelectionChangedConverter" />