我正在尝试在WPF中使用MVVM执行listbox更改事件。请告诉我如何执行selectionchanged事件。
你可以使用以下步骤完成:
System.Windows.Interactivity
的引用。xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
。然后
<ListBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding YourCommand}"
CommandParameter="{Binding YourCommandParameter}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
你应该将列表框的SelectedItem
属性绑定到ViewModel上的属性:
<ListBox SelectedItem="{Binding SelectedItem}" ...>
....
</ListBox>
在该属性中,始终会有从ListBox中选择的项。如果您真的需要在选择更改时执行某些操作,可以在该属性的setter方法中执行:public YourItem SelectedItem
{
get { return _selectedItem; }
set
{
if(value == _selectedItem)
return;
_selectedItem = value;
NotifyOfPropertyChange("SelectedItem");
// selection changed - do something special
}
}
SelectionMode="Multiple"
和 "Extended"
,这仅适用于选择的第一项 - 当您展开选择时**SelectedItem
不会改变**。在这种情况下,接受的答案可以正常工作(并允许将ListBox的 SelectedItems
列表作为命令参数传递:`CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ListBox}, Path=SelectedItems}")。 - spacer你可以将ListBox的SelectionChanged事件绑定到ViewModel中的命令。
"xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
- Muhammad Ummarhttp://schemas.microsoft.com/xaml/behaviors
。 - Zev Spitz