how to handle WPF listbox selectionchanged event using MVVM
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
}
}
You can do it using
- Add reference to
System.Windows.Interactivity
in your project - 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>