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?
There are a couple of options:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With