本文介绍了WPF - 在View Model中处理来自用户控件的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVVM模式构建一个WPF应用程序(两者都是我的新技术)。我使用用户控件为简单的可重用功能,不包含业务逻辑,MVVM模式构建应用程序逻辑。假设一个视图包含我的用户控件来触发事件,并且我想为事件添加一个事件处理程序。该事件处理程序应该在视图的视图模型中,因为它包含业务逻辑。问题是 - 视图和视图模型只通过绑定连接;如何使用绑定连接事件处理程序?甚至有可能(我怀疑不是)如果没有 - 应该如何处理视图模型中控件的事件?也许我应该使用命令或INotifyPropertyChanged?

解决方案

一般来说,这是一个很好的MVVM实践,以避免代码背后的代码,如果您在用户控件中使用事件就会如此。所以,如果可能,请使用 INotifyPropertyChanged ICommand



据说,根据你的项目和你的实际情况,有时候使用控件的代码更有意义。



我有几次使用这样的东西:

  private void textBox1_MouseDoubleClick(object sender,MouseButtonEventArgs e)
{
MyViewModel vm = this.DataContext as MyViewModel;
vm.MethodToExecute(...);
}

您还可以考虑,关于这个的更多信息和在这里找到的实现: p>


I’m building a WPF application using MVVM pattern (both are new technologies for me). I use user controls for simple bits of reusable functionality that doesn’t contain business logic, and MVVM pattern to build application logic. Suppose a view contains my user control that fires events, and I want to add an event handler to that event. That event handler should be in the view model of the view, because it contains business logic. The question is – view and the view model are connected only by binding; how do I connect an event handler using binding? Is it even possible (I suspect not)? If not – how should I handle events from a control in the view model? Maybe I should use commands or INotifyPropertyChanged?

解决方案

Generally speaking, it is a good MVVM-practice to avoid code in code behind, as would be the case if you use events in your user controls. So when possible, use INotifyPropertyChanged and ICommand.

With that said, depending on your project and how pragmatic you are, some times it makes more sense to use the control's code behind.

I have at a few occasions used something like this:

private void textBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    MyViewModel vm = this.DataContext as MyViewModel;
    vm.MethodToExecute(...);
}

You could also consider Attached Command Behaviour, more info about this and implementations to find here:

Firing a double click event from a WPF ListView item using MVVM

这篇关于WPF - 在View Model中处理来自用户控件的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:42