Working with WPF it is good practice to keep your xaml.cs code behind files small and clean. The MVVM pattern helps achieving this goal through Data Bindings and Command Bindings where any business logic is handled in the ViewModel classes.
I am using the principles of the MVVM pattern and my code-behind files are rather nice and clean. Any button click events are handled using Command Bindings, and there are a few more controls that also supports Command Binding. However, there are several events on controls that does not have the Command and CommandParameter properties, and hence I see no direct way for using bindings. What is the best approach for getting rid of logic in the code-behind files for such events? E.g. handling mouse events inside a control.
A nice approach for this is to use an attached behaviour. The behaviour itself can hook the event you need and fire the appropriate command with the parameters you want. It’s essentially the same code, but it just remove it from your code behind and lets you express your intent purely in XAML.
There are several example behaviours on CodePlex, or a here’s a basic sample that executes a command:
}
You can then use the System.Windows.Interactivity namespace (the assembly is included with Blend 3) to hook the event and fire the command as follows:
For more complicated events with multiple parameters you may need to create a specific Behaviour, rather than using a generic one like the example above. I generally prefer to create my own type to store parameters, and map to it, rather than having a specific EventArgs requirement in my ViewModel.
*One thing I should add is that I’m definately not a “0 code in the Code Behind” kind of guy, and I think enforcing this religiously is missing the point of MVVM somewhat. As long as the code behind contains no logic, and therefore nothing that really need to be under test, then I can live with some small pieces of code behind for “bridging the gap” between View and ViewModel. This is also sometimes necessary if you have a “smart view”, as I generally call it, such as a browser control, or something you need to commmunicate with from your ViewModel. Some people would get pitchforks out for even suggesting such a thing, that’s why I left this bit until last and answered your question first :-)*