how to handle WPF listbox selectionchanged event using MVVM

前端 未结 3 1000
时光取名叫无心
时光取名叫无心 2020-12-15 21:09

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

相关标签:
3条回答
  • 2020-12-15 21:23

    You can do it using

    1. Add reference to System.Windows.Interactivity in your project
    2. in XAML add 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>
    
    0 讨论(0)
  • 2020-12-15 21:31

    You would bind the SelectedItem property of the listbox to your property on the 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:

    public YourItem SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            if(value == _selectedItem)
                return;
    
            _selectedItem = value;
    
            NotifyOfPropertyChange("SelectedItem");
    
            // selection changed - do something special
        }
    }
    
    0 讨论(0)
  • 2020-12-15 21:40

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

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

    0 讨论(0)
提交回复
热议问题