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

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

问题描述

从 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 组件.我想在鼠标移到 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 轻量级框架

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天全站免登陆