如何在视图模型中获取鼠标位置 [英] How do I get mouse positions in my view model

查看:91
本文介绍了如何在视图模型中获取鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从MVVM设计模式中,视图模型不应了解视图.但就我而言,我需要视图和模型,我的意思是:

From MVVM Design pattern, the viewmodel should not know the view. But in my case, I need the view and the model, I mean :

在我的窗口中,有一个图像组件.当鼠标移到Image组件上并将其保存到模型中时,我想获取鼠标位置.

In my window, I've an Image component. I'd like to get mouse position when mouse moves over the Image component and save it into my model.

后面的代码应该是:

void Foo_MouseMove(objet sender, MouseEventArgs e)
{
  model.x = e.getPosition(this.imageBox).X; 
  model.y = e.getPosition(this.imageBox).Y;
}

问题是:我需要this.imageBox和MouseEventArgs,所以需要两个View元素.

The problem is : I need this.imageBox and MouseEventArgs, so two View element.

我的问题是:如何使用MVVM方法处理此案?

My question is : How to deal with this case using the MVVM approach ?

我使用MVVM light框架

I use MVVM light framework

推荐答案

最后使用EventConverter找到了答案:

Finnally found an answer, using a EventConverter :

  public class MouseButtonEventArgsToPointConverter : IEventArgsConverter
    {
        public object Convert(object value, object parameter)
        {
            var args = (MouseEventArgs)value;
            var element = (FrameworkElement)parameter;
            var point = args.GetPosition(element);
            return point;
        }
    }

此转换器使我可以处理Point而不是图形组件.

This converter allows me to deal with Point and not with graphics components.

XML:

        <i:Interaction.Triggers>
            <i:EventTrigger EventName="MouseMove">
                <cmd:EventToCommand
                 Command="{Binding Main.MouseMoveCommand, Mode=OneWay}"
                 EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}"
                 EventArgsConverterParameter="{Binding ElementName=Image1}"
                 PassEventArgsToCommand="True" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

这篇关于如何在视图模型中获取鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆