Which is the difference between to use a dependecy property as command and to use a custom routed event?

Viewed 25

I have a user control with a datagrid. I would like to notify to the main view that a user doble click in an intem of this datagrid. I would like to notify the doble clicked item too.

For that, the first solution that I thought it was to use a custom routed event, how I could see in the Microsoft documentation.

But I have seen that another option it is to define a dependency property that is a ICommand. This it would be the code:

void RaiseItemDobleClickEvent(object sender, MouseButtonEventArgs e)
     {
       ItemDobleClickCommand.Execute(null);
     }
    
     public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("ItemDobleClickCommand", typeof(ICommand), typeof(Window011UC1));
     // Declare a get accessor method.
     public static ICommand GetItemDobleClickCommand(UIElement target) => (ICommand)target.GetValue(CommandProperty);
     // Declare a set accessor method.
     public static void SetItemDobleClickCommand(UIElement target, ICommand value) => target.SetValue(CommandProperty, value);
    
    
     public ICommand ItemDobleClickCommand
     {
       get { return (ICommand)GetValue(CommandProperty); }
       set { SetValue(CommandProperty, value); }
     }
    
     public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("ItemDobleClickCommandParameter", typeof(object), typeof(Window011UC1));
     public object ItemDobleClickCommandParameter
     {
       get { return (object)GetValue(CommandParameterProperty); }
       set { SetValue(CommandParameterProperty, value); }
     }
   }
 }

Then in the main view I could use it in this way:

<Label Content="DoubleClick UC2" MouseDoubleClick="{Binding RaiseItemDobleClickEvent}"/>

I see that it is two ways to do the same, but I don't know which are the differences, when to use one solution or another or the advantages or disadvantages of each one.

So when to use a depency property as command and when to use a routed event?

Thanks.

1 Answers

Well, en event is an event and the other approach is commonly referred to as an attached behaviour and it's frequently used in MVVM apps.

You cannot bind an event to a property like this though:

MouseDoubleClick="{Binding RaiseItemDobleClickEvent}"

What you do is that you define a custom dependency property and register a callback that invokes the command. You'll find an example here.

The XAML would look something like this:

<Label ... local:YourClass.MouseDoubleClickCommand="{Binding YourViewModelCommand}" />
Related