开发者

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

开发者 https://www.devze.com 2022-12-24 02:12 出处:网络
In my program I nee开发者_StackOverflowd 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 p

In my program I nee开发者_StackOverflowd 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:

  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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消