如何使用MVVM处理WPF listbox selectionchanged事件

sku*_*mar 16 wpf mvvm

我正在尝试使用MVVM在WPF中执行listbox更改的事件.请让我知道如何做这个选择改变事件.

Dan*_*rth 33

您可以将SelectedItem列表框的属性绑定到ViewModel上的属性:

<ListBox SelectedItem="{Binding SelectedItem}" ...>
    ....
</ListBox>
Run Code Online (Sandbox Code Playgroud)

在属性中,始终会有ListBox中的选定项.如果您确实需要在选择更改时执行某些操作,则可以在该属性的setter中执行此操作:

public YourItem SelectedItem
{
    get { return _selectedItem; }
    set
    {
        if(value == _selectedItem)
            return;

        _selectedItem = value;

        NotifyOfPropertyChange("SelectedItem");

        // selection changed - do something special
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记将TwoWay绑定指定为模式. (6认同)
  • @ScottNimrod:这应该是默认值. (4认同)

Muh*_*mar 32

你可以用它来做

  1. System.Windows.Interactivity在项目中添加引用
  2. 在XAML中添加 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>
Run Code Online (Sandbox Code Playgroud)