MVVM Madness: Commands

2019-03-07 19:26发布

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:

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.

7条回答
ら.Afraid
2楼-- · 2019-03-07 20:25

Decoupling is one of the major feature of MVVM. If suppose you want to change say view or binded model to it. How much easy it is for your application?

Take an example where View1 and View2 both share the same ViewModel. Now will you implement the code behind method for both.

Also, suppose if you need to change the viewmodel for a view on later stage your command will get fail as view model is changed and statement

MyViewModel vm = this.DataContext as MyViewModel;

will return null and hence code crash. So there comes an extra burden to change the code behind also. These kind of scenarios will arise if you do it in this way.

Of course there are many ways to achieve the same thing in programming but which one is best will lead to best approach.

查看更多
登录 后发表回答