简体   繁体   English

使用MVVM模式在WPF中使用命令

[英]Using Commands in WPF using the MVVM pattern

I am faced with a problem that might be known by other developers and I am trying to figure it out and understand it well. 我面临着其他开发人员可能知道的问题,并且我试图弄清楚并很好地理解它。 It doesn't have to be directly connected to MVVM/WPF, it can also be connected to other methodologies like MVC and MVP . 它不必直接连接到MVVM / WPF,也可以连接到其他方法,例如MVC和MVP。

Lets assume I have a shop cart Model that has its own Service, addItem and deleteItem Methods and calculates the price of the shop cart etc. 假设我有一个购物车模型,该模型具有自己的Service,addItem和deleteItem方法,并计算购物车的价格等。

Now in my View I display this shop cart and when I want to show the total sum of the shop cart I click on a button to trigger the method that take cares of this. 现在,在我的视图中,我将显示此购物车,当我想显示购物车的总金额时,我单击一个按钮以触发负责此操作的方法。

Here comes the problem: How can I bind the Method (or Command) to the Button? 问题来了:如何将方法(或命令)绑定到按钮? I know that I have to use ICommand , but by using this interface I kind of break the rules of responsibility separation. 我知道我必须使用ICommand ,但是通过使用此接口,我有点违反了责任分离的规则。 How can I implement, without break the rules of the MVVM pattern. 我如何实现而不破坏MVVM模式的规则。

例:

What you call PresentationModel , is the ViewModel in WPF, which is the DataContext of the View. 您所说的PresentationModel是WPF中的ViewModel ,它是View的DataContext
This ViewModel holds an instance of ShopCart . 此ViewModel拥有ShopCart的实例。 It also holds the commands, so that the view can bind to them. 它还包含命令,以便视图可以绑定到它们。
The command, lets name it CalculatePrice should just invoke the calculatePrice() method of the ShopCart . 该命令命名为CalculatePrice应该只调用ShopCartcalculatePrice()方法。

The question is, how do you define it that way: 问题是,如何定义这种方式:
Well, I like using RelayCommand , which allows you to define commands using lambda expressions. 好吧,我喜欢使用RelayCommand ,它允许您使用lambda表达式定义命令。

So then you can have a property public RelayCommand CalculatePrice , which you define in the constructor: 因此,您可以拥有一个public RelayCommand CalculatePrice属性,您可以在构造函数中定义该属性:

public ViewModel(){
    CalculatePrice = new RelayCommand(param => this.ShopCart.calculatePrice());
}

That way, you can bind the CalculatePrice command to the button, which then executes ShopCart.calculatePrice() . 这样,您可以将CalculatePrice命令绑定到该按钮,然后执行ShopCart.calculatePrice()

If I understood correctly, in your view you display a set of ShopCarts, and you want to be able to call the ShopCart.calculatePrice() method. 如果我理解正确,那么在您看来,您将显示一组ShopCarts,并且您希望能够调用ShopCart.calculatePrice()方法。 I would say, what you need to do, is to store the ICommand object in your ViewModel, and bind the ShopCart to the CommandParameter property. 我要说的是,您需要做的是将ICommand对象存储在ViewModel中,并将ShopCart绑定到CommandParameter属性。 This way, you will receive the ShopCart as the parameter of the CanExecute and Execute methods. 这样,您将收到ShopCart作为CanExecuteExecute方法的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM