Reputation: 193472
For those doing pure MVVM, how do you handle a ComboBox SelectionChanged event without reverting to code behind?
I tried e.g. AttachedBehaviors but Event="SelectedChanged" is not supported:
<ComboBox>
<ComboBoxItem Content="Test1">
<c:CommandBehaviorCollection.Behaviors>
<c:BehaviorBinding Event="SelectionChanged"
Command="{Binding SelectedChanged}"
CommandParameter="MainBorder123"/>
</c:CommandBehaviorCollection.Behaviors>
</ComboBoxItem>
<ComboBoxItem Content="Test2"/>
<ComboBoxItem Content="Test3"/>
</ComboBox>
Upvotes: 39
Views: 67524
Reputation: 19521
For .NET CORE and above
Install Microsoft.Xaml.Behaviors.Wpf package
Use the namespace
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
Then the comobox should be
<ComboBox ItemsSource="{Binding Items}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
notice: there are no changes to the code at all, the only needed thing is the Nuget package and updating the namespace
Upvotes: 3
Reputation: 2111
This post is quite old, but since I got the same issue. Here is how I solved it (using framework 4.0) : the idea is to use System.Windows.Interactivity.
In the XAML :
<ComboBox ItemsSource="{Binding Items}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChangedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
Then you just need to implement the SelectionChangedCommand in your viewmodel.
Upvotes: 86
Reputation: 17043
I'm not sure if what you're after is possible, but the way I do it is to simply bind the SelectedItem to a property on view model. Then within the property setter, I call any custom code that I want to happen i.e. setting other properties based on rule. If I need the selected item to be bound to an object aswell (for other bound controls to update) I set this in the setter too and send out a notification.
Upvotes: 27
Reputation: 1806
You would use a data trigger to trigger an event on a different UI element such as "enable / disable, or visible /invisible"
If you want the selected element to show the object data in other UI elements then you would use data binding and set the datacontext of the UI data display elements to be bound to the currently selected item in the combo box.
Upvotes: 3