What's a good method to bind Commands to Events? In my WPF app, there are events that I'd like to capture and process by my ViewModel but I'm not sure how. Things like losing focus, mouseover, mousemove, etc. Since I'm trying to adhere to the MVVM pattern, I'm wondering if there's a pure XAML solution.
Thanks!
In order to handle events, you must have some code that attaches itself to the event and executes your command in response. The final goal is to have in XAML:
In order to achieve this you need to define an attached property for each event that you want to handle. See this for an example and a framework for doing this.
Execute Command, Navigate Frame, and Delegating Command behaviour is a pretty good pattern. It is also can be used in the Expression Blend.
On the "best practices" side, you should think twice before converting an event to a command. Normally, command is something user does intentionaly, an event most often is just an interaction trail, and should not leave the view boundaries.
Use System.Windows.Interactivity
Make sure your project references the assembly System.Windows.Interactivity.
Source: MSDN Blog Executing a command from an event of your choice
I implemented it using Attached Properties and Reflection. I cannot say it is the best implementation, but I will maybe improve it and it may be a good start for you.
Examples of usage:
View
Model
I don't think you can use it in pure XAML, but take a look at the Delegate Command.
Have a look at Marlon Grech's Attached Command Behaviour, it could be exactly what you're looking for