MVVM Madness: Commands
Posted
by JP
on Stack Overflow
See other posts from Stack Overflow
or by JP
Published on 2010-01-18T17:04:42Z
Indexed on
2010/03/18
1:31 UTC
Read the original article
Hit count: 685
I like MVVM. I don't love it, but like it. Most of it makes sense. But, I keep reading articles that encourage you to write a lot of code so that you can write XAML and don't have to write any code in the code-behind.
Let me give you an example.
Recently I wanted to hookup a command in my ViewModel to a ListView MouseDoubleClickEvent. I wasn't quite sure how to do this. Fortunately, Google has answers for everything. I found the following articles:
- http://blog.functionalfun.net/2008/09/hooking-up-commands-to-events-in-wpf.html
- http://joyfulwpf.blogspot.com/2009/05/mvvm-invoking-command-on-attached-event.html
- http://sachabarber.net/?p=514
- http://geekswithblogs.net/HouseOfBilz/archive/2009/08/27/adventures-in-mvvm-ndash-binding-commands-to-any-event.aspx
- http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/
While the solutions were helpful in my understanding of commands, there were problems. Some of the aforementioned solutions rendered the WPF designer unusable because of a common hack of appending "Internal" after a dependency property; the WPF designer can't find it, but the CLR can. Some of the solutions didn't allow multiple commands to the same control. Some of the solutions didn't allow parameters.
After experimenting for a few hours I just decided to do this:
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
ListView lv = sender as ListView;
MyViewModel vm = this.DataContext as MyViewModel;
vm.DoSomethingCommand.Execute(lv.SelectedItem);
}
So, MVVM purists, please tell me what's wrong with this? I can still Unit test my command. This seems very practical, but seems to violate the guideline of "ZOMG... you have code in your code-behind!!!!" Please share your thoughts.
Thanks in advance.
© Stack Overflow or respective owner