mouse/loaded event

Topics: Prism v4 - WPF 4
Oct 10, 2011 at 8:44 PM
Edited Oct 10, 2011 at 8:45 PM


what is the best practice for implementing behaviors in WPF application? Please suggest.

for eg : mouseclick, loaded, selected


Oct 11, 2011 at 7:36 PM


The Prism guidance is intended to be used primarily with the MVVM design pattern. In this pattern you have a view, which represents the UI, and a view model, which contains and exposes the operational logic and data for the view through commands and properties. Usually, the view and the view model interact with each other through data bindings. Like this, this pattern allows to develop more decoupled, maintainable and testable applications.

For example, when implementing the MVVM pattern, you can bind the command property of a button to a property in the view model that exposes a command (this can be easily done using the DelegateCommand class shipped with the Prism library) and when the button is clicked, the aforementioned command will be executed.

For other events (like for example "loaded," "selected," "mouseover", etc) you can implement you custom command behaviors, which could allow you to attach commands to you controls according to your needs. The commands attached using those behaviors can be DelegateCommands exposed by the view model through a property, and should be executed in the same way that a command attached to the click event of a button. To implement your custom command behaviors you might find the following thread useful:

If the cost of implementing your custom commands behaviors make the aforementioned approach unusable in your scenario, you can have an event handler in the code behind of the view that could obtain the required command from the view model (through its properties) and execute it. If this approach does not fit your scenario, you could invoke a public method exposed by the view model instead; however, take into account that you will need to cast the view model (which should be the data context of the view) to its specific type or interface in order to do it.

Also, it is important to note that if the interaction represented by that event in the view will only cause visual modifications to your view (e.g. highlighting a textbox), you don't need to involve your view model. These events could be handled entirely on the code behind of the view.

You can find more information about the MVVM pattern in the following links:

I hope you find this useful,

Damian Cherubini