如何使用 MVVM 处理 WPF 列表框选择更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12297502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:30:36  来源:igfitidea点击:

how to handle WPF listbox selectionchanged event using MVVM

wpfmvvm

提问by skumar

I am trying to perform listbox changed event in WPF using MVVM. Please let me know how to do this selectionchanged event.

我正在尝试使用 MVVM 在 WPF 中执行列表框更改事件。请让我知道如何执行此 selectionchanged 事件。

回答by Daniel Hilgarth

You would bind the SelectedItemproperty of the listbox to your property on the ViewModel:

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

<ListBox SelectedItem="{Binding SelectedItem}" ...>
    ....
</ListBox>

In the property there always will be the selected item from the ListBox. If you really need to do something when the selection changes you can do it in the setter of that property:

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

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

        _selectedItem = value;

        NotifyOfPropertyChange("SelectedItem");

        // selection changed - do something special
    }
}

回答by Muhammad Ummar

You can do it using

你可以使用

  1. Add reference to System.Windows.Interactivityin your project
  2. in XAML add xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
  1. System.Windows.Interactivity在您的项目中添加引用
  2. 在 XAML 中添加 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

Then

然后

<ListBox>
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
      <i:InvokeCommandAction Command="{Binding YourCommand}"
                             CommandParameter="{Binding YourCommandParameter}" />
    </i:EventTrigger>
  </i:Interaction.Triggers>
</ListBox>

回答by ajd.nas

you can binding ListBox SelectionChanged Event to command in your ViewModel.

您可以将 ListBox SelectionChanged 事件绑定到 ViewModel 中的命令。

see this answer https://stackoverflow.com/a/18960028/5627499

看到这个答案 https://stackoverflow.com/a/18960028/5627499