1

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 .

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.

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. How can I implement, without break the rules of the MVVM pattern.

Example:

Tseng
  • 61,549
  • 15
  • 193
  • 205
Elad Israeli
  • 131
  • 2
  • 11
  • you will implement it in ViewModel of the VIew – Ehsan Sajjad Jan 26 '16 at 13:40
  • 1
    Look at implementation of ICommand https://msdn.microsoft.com/en-us/library/system.windows.input.icommand(v=vs.110).aspx and http://stackoverflow.com/questions/1135983/wpf-icommand-vs-routedcommand – kenny Jan 26 '16 at 13:50
  • Using `ICommand` in ViewModel is not a violation of MVVM pattern, as commands are a presentation concern and hence belong to the ViewModel. @Domysee pointed it already out, in the command you just relay it to the service layer. Remember, that you may rise a notification or set the new price to a property that does rise the notification it its setter – Tseng Jan 26 '16 at 15:56

2 Answers2

4

What you call PresentationModel, is the ViewModel in WPF, which is the DataContext of the View.
This ViewModel holds an instance of 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.

The question is, how do you define it that way:
Well, I like using RelayCommand, which allows you to define commands using lambda expressions.

So then you can have a property public RelayCommand CalculatePrice, which you define in the constructor:

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().

Domysee
  • 12,718
  • 10
  • 53
  • 84
2

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. 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. This way, you will receive the ShopCart as the parameter of the CanExecute and Execute methods.

DAAlex
  • 446
  • 5
  • 9