When I started my last WPF project using MVVM by referring Josh Smith’s article ,I was very much excited about the way it separates the view and model.But after going some way, I got issues.The reason was how to execute command on events like MouseOver and MouseDown.In the sample which I got,the commands were just bound to the Button.Command property.It was possible because the Button implements ICommandSource interface.In that case also we can’t invoke command on events other than Button.Click.
After a tough Google ,I found this article in Jaco Karsten’s blog which allows to invoke command on any control any event.The only thing is we have to use an Expression Blend 3 dll named Microsoft.Expression.Interactivity which have its own attached Interaction trigger mechanism along with Jaco’s CommandAction class.Attached trigger mechanism allows us to add a EventTrigger and CommandAction class will invoke a command when the trigger if fired.Life became cool again.Thanks to Jaco.
Implemention of Interaction.Triggers and Command action.Command will execute when the trigger fired
When this comes to Surface,I again saw a hurdle.We can’t invoke command on attached events.For example we can’t invoke command on s:Contacts.ContactDown.
After reflecting the class EventTrigger present in the Microsoft.Expression.Interactivity dll, I came to know that it is using reflection to find out the event from it’s EventName property which is not applicable in the case of attached events.Hence I was forced to create a new trigger which fires on attached event by inheriting EventTriggerBase<T> class.
Implementation of RoutedEventTrigger
A property named RoutedEvent of type RoutedEvent is being added.In the overridable method OnAttached, I attached a handler to the RoutedEvent and in the handler call the OnEvent method present in the base.That in turn calls all the actions associated with that trigger.For more details see the code below
Executes touch command on Contacts.ContactDown event.