2
votes

I've been searching for some information on binding WPF events to commands defined in a ViewModel.

I know there are many frameworks that can do it for me, but I don't want to use any of them, but implement something from scratch to see how it's working.

I've found this article: http://blog.functionalfun.net/2008/09/hooking-up-commands-to-events-in-wpf.html

and in general it's very good. However, I've got two questions:

  1. I'd like to have a command with a parameter and bind the parameter to a property in XAML (like CommandParameter={Binding ...}). How to extend the article to handle this ?

  2. In my understanding in this implementation to use, let's say, a MouseDoubleClick event in two different UI Elements, I need to define two different properties and attach them to each of the types I want to extend. Isn't there a smarter way (i.e. defining an Attached Property once and then use it in all the elements)?

1
You will need to use an extended framework to do this. The most common is Expression Blend which offers what you are looking for. - Xcalibur37
Really ? Are you sure this can't be done without referencing any external library ? - Alojzy Leszcz
You can see my post to find a sample for binding events to viewmodel. Regarding q1: the behaviour should implement an Attached Property containing the ICommand parameters to use. Regarding q2: if I understand your needs, you can use just one Attached Property shared among multiple commands, but I guess it's clearer and better to define an Attached Property foreach ICommand. - trix
Works fine - thanks :). - Alojzy Leszcz

1 Answers

1
votes

Please consider using EventToCommand behavior from the MVVM Light library. The related article: Commands, RelayCommands and EventToCommand).

Also, there is an alternative to EventToCommand behavior (quote from the article):

Note: You can also use an InvokeCommandAction instead of MVVM Light’s EventToCommand. This behavior is part of the System.Windows.Interactivity DLL. It is almost equivalent to EventToCommand, but without some of the advanced features.

The example of using InvokeCommandAction mentioned in the note has been found here: Executing a command from an event of your choice.