Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using MVVM, what to do when a control doesn't have a "Command" property?

Tags:

c#

.net

mvvm

wpf

In my program I need a way to click on an Image control, the program takes in the X,Y position of where the click took place, and then produce a rectangle around that position. My problem is that I'm using MVVM, so all my code is in a separate file (ViewModel file rather than the code-behind file). The Image control doesn't have a Command property so what's the best way to implement this?

like image 509
Harry Avatar asked Mar 26 '10 17:03

Harry


2 Answers

There are a couple of options:

  1. Use Code behind. It isn't a rule that you can't use code behind in MVVM - and this is a situation where it's potentially appropriate. Just have your code behind do nothing but route the coordinates to your ViewModel, and have the actual "logic" for processing coords be in the VM, and it's still MVVM.
  2. Use some form of attached property, such as a Blend Trigger, to wire this up. Here's a blog post describing one option (based on the MVVM Helpers library).

Personally, in this situation, I'd probably just use an event handler in code behind. My rationale would be that the click handling on the image is really a view concern anyways - it's just interaction. The ViewModel could just have a method or a command that took a new Point, which could be fired from your code behind event handler, and do the actual processing.

This keeps your logic in the ViewModel and very testable (processing a new point is easy to test). The View "code" is really very simple, and view related.

like image 194
Reed Copsey Avatar answered Nov 10 '22 20:11

Reed Copsey


Completely agree with @Reed, This looks really like you need to do some View specific calculation on your click, So better do it in the code behind. Or else you can create a customer control which does all those mouse handling as well as co-ordinate handling logic and expose your desired 'Point' dependacy properties. Then it is a matter of some ViewModel binding to the newly created Custom control.

Now the answer to the subject of your question 'Using MVVM, what to do when a control doesn’t have a “Command” property?' - Suppose you need to give click command on an Image, the trick I would do is to place a button and override the Button.Controltemplate and place the image inside that. So that the Image will be the visual for the button and I can get my Command property.

like image 3
Jobi Joy Avatar answered Nov 10 '22 18:11

Jobi Joy