Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle WPF listbox selectionchanged event using MVVM

Tags:

mvvm

wpf

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

like image 257
skumar Avatar asked Sep 06 '12 09:09

skumar


2 Answers

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>
like image 73
Muhammad Ummar Avatar answered Nov 12 '22 17:11

Muhammad Ummar


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
    }
}
like image 34
Daniel Hilgarth Avatar answered Nov 12 '22 17:11

Daniel Hilgarth