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>
3. write new behaviour with dependency property
SelectionChangedEvent with PropertyChangecallBack.
- public static class SelectionChangedBehavior {
- private static readonly DependencyProperty SelectionChangedEvent =
- DependencyProperty.RegisterAttached(
- "SelectionChangedEvent",
- typeof(ICommand),
- typeof(SelectionChangedBehavior),
- new PropertyMetadata(null, new ExecuteCommandOnRoutedEvent(Selector.SelectionChangedEvent).PropertyChangedHandler));
-
- public static void SetSelectionChangedEvent(DependencyObject dependencyObject, ICommand value) {
- dependencyObject.SetValue(SelectionChangedEvent, value);
- }
-
- public static ICommand GetSelectionChangedEvent(DependencyObject dependencyObject) {
- return (ICommand) dependencyObject.GetValue(SelectionChangedEvent);
- }
- }
4. Finally, implement propertyChangecallback routed event. Here, each UIElement of WPF can add and remove event handlers.
- public class ExecuteCommandOnRoutedEvent {
- private readonly RoutedEvent routed;
-
- private DependencyProperty property;
-
- public ExecuteCommandOnRoutedEvent(RoutedEvent @event) {
- routed = @event;
- }
-
- private void ManageEventHandlers(DependencyObject sender, object oldValue, object newValue) {
- var element = sender as UIElement;
-
- if (element == null) {
- return;
- }
-
- if (oldValue != null) {
- element.RemoveHandler(routed, new RoutedEventHandler(CommandEventHandler));
- }
-
- if (newValue != null) {
- element.AddHandler(routed, new RoutedEventHandler(CommandEventHandler));
- }
- }
-
- private void CommandEventHandler(object sender, RoutedEventArgs e) {
- var dp = sender as DependencyObject;
- if (dp == null) {
- return;
- }
-
- var command = dp.GetValue(property) as ICommand;
-
- if (command == null) {
- return;
- }
-
- if (command.CanExecute(e)) {
- command.Execute(e);
- }
- }
-
- public void PropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e) {
- property = e.Property;
- var oldValue = e.OldValue;
- var newValue = e.NewValue;
- ManageEventHandlers(sender, oldValue, newValue);
- }
- }
The main view model and child view models all have properties bound to MainView, you can refer to the code to get the full working solution.
Conclusion
Here, we learned how to write behaviors and how to add routed events to change View to viewmodel using behaviors.