tags:

views:

49

answers:

2

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?

+5  A: 

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.

Reed Copsey
+1 for suggesting code behind. So many people are against it it's good to see others recommending it. But only when appropriate.
Cameron MacFarland
OK, thanks for clarifying.
Harry
+1  A: 

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.

Jobi Joy
A WPF book I read (can't remember which) said when doing WPF to pick the control with the behaviour you want and make it look the way you want through styling. A button made to look like an image is exactly what the author was describing.
Cameron MacFarland