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.
Example of binding ListBox SelectionChanged
Event to command in your ViewModel
<ListBox x:Name="myListBox" ItemsSource="{Binding SomeCollection}">
<ie:Interaction.Triggers>
<ie:EventTrigger EventName="SelectionChanged">
<ie:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}" CommandParameter="{Binding ElementName=myListBox, Path=SelectedItem}"/>
</ie:EventTrigger>
</ie:Interaction.Triggers>
</ListBox >
In your ViewModel
:
public class myViewModel
{
public myViewModel()
{
SelectedItemChangedCommand = new DelegateCommand<object>((selectedItem) =>
{
// Logic goes here
});
}
public List<SomeData> SomeCollection { get; set; }
public DelegateCommand<object> SelectedItemChangedCommand { get; set; }
}
This particular example uses Prism MVVM Framework, but you can apply the same idea with any other MVVM framework you are using as well.
Hope this helps
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:
<ListBox ItemsSource="{Binding Items}" SelectedIndex="{Binding SelectedIndex}" />
Items
is the collection of items we bind to.