We already saw one example how to convert Event into Command here. But if we want to consume more than one event, then we have to write lots of repetitive code. Take a look at the following example, here we handle SelectionChagne and MouseDouble click event of Selector and Control classes respectively.
Let’s reduce the duplicative work step by step. At first step we can remove the ICommand type properties so we don’t need to call GetValue and SetValue methods of DependencyObject class and don’t have to make it a child class of DependencyObject.
Then we noticed that we have to write a callback method and event handler method for all the event. We can create a separate class to perform this functionality. I simply extract the code of callback method and event handler and insert into my new class EventBahavior. To make it compile I have to create two fields of DependencyProperty and RoutedEvent type. To make sure we always have RoutedEvent we created our own constructor and passed routed event as a parameter. Here is our class.
We can create an object of this class to make our life easy. Here is updated version of our class to define two event in selector class.
It is much less code as compare to the previous version. But here we are creating multiple object of our helper class i.e. EventBahavior. We can encapsulate this in factory class and make constructor of factory class private so no one can create an object of that class. Here is our factory class.
Here is a usage of our SelectorBehavior class using this Factory class.
In this way we reduces lots of our duplicated code if we are going to convert more than one event into command.
Here is simple usage of this in XAML