I have a list box in my WPF application. I know how to use the selectionchanged event. However I am trying to follow the MVVM design. However I am not sure how to do this.>
using SelectionChanged
with MVVM is quite simple:
An approach could be to bind to the SelectedIndex
property of the ListBox
and in the property setter in the VM, act accordingly as it would be triggered whenever the property changes.
Example: Here
In this example whenever the selected index changes, the value of that item is increased by one.
the main bit is:
public int SelectedIndex {
get {
return _selectedIndex;
}
set {
if (_selectedIndex == value) {
return;
}
// At this point _selectedIndex is the old selected item's index
_selectedIndex = value;
// At this point _selectedIndex is the new selected item's index
RaisePropertyChanged(() => SelectedIndex);
}
}
xaml would just be:
Items
is the collection of items we bind to.