Introduction
In this post, we'll learn how to bind the Combo box selectionchange event using behaviors and routed events. I will demonstrate how to bind the combo box selection change event in WPF using MVVM using ICommand interface.
This ICommand will be registered with Combo box(UIElement) using behavior and will be executed when selection changes. This approach can be used for any UI Element selection change using MVVM.
Implementation
1. Have your CustomCommand : ICommand execute when Command is triggered from view.
The ICommand Interface is used for updating models from view using MVVM. It is defined under System.Windows.Input namespace. Let's jump to the code in order to understand the topic.
- public class MyCustomCommand < T >: ICommand {
- private Action < T > execute;
- private Func < T, bool > canExecute;
- public event EventHandler CanExecuteChanged {
- add {
- CommandManager.RequerySuggested += value;
- }
- remove {
- CommandManager.RequerySuggested -= value;
- }
- }
- public MyCustomCommand(Action < T > execute, Func < T, bool > canExecute = null) {
- this.execute = execute;
- this.canExecute = canExecute;
- }
- public bool CanExecute(object parameter) {
- return this.canExecute == null || this.canExecute((T) parameter);
- }
- public void Execute(object parameter) {
- this.execute((T) parameter);
- }
- }
2. Create your XAML with a Combo box and attach the behavior with that. The next step will show how to create this behavior and how selection change triggers from view to view models.
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="*"></RowDefinition>
- <RowDefinition Height="100"></RowDefinition>
- </Grid.RowDefinitions>
- <DataGrid x:Name="McDataGrid" Margin="0" AutoGenerateColumns="False" ItemsSource="{Binding MainItems}">
- <DataGrid.Columns>
- <DataGridTextColumn Width="*" Binding="{Binding Name}" Header="Name" IsReadOnly="True"/>
- <DataGridTemplateColumn MinWidth="200" Width="Auto" Header="Departments">
- <DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <ComboBox ItemsSource="{Binding Items}"
- SelectedItem="{Binding Department}"
- local:SelectionChangedBehavior.SelectionChangedEvent="{Binding SelectionChangeCommand}">
- </ComboBox>
- </DataTemplate>
- </DataGridTemplateColumn.CellTemplate>
- </DataGridTemplateColumn>
- </DataGrid.Columns>
- </DataGrid>
- <TextBlock Grid.Row="1" Text="{Binding Message}"/>
- </Grid>

Sourav Kumar DasPosted Dec 11, 2019, 10:57 PM
Nice useful article. Thanks for sharing.