【问题标题】:Get mouse coordinates when click on button [duplicate]单击按钮时获取鼠标坐标[重复]
【发布时间】:2019-02-14 18:34:13
【问题描述】:

我有一个显示图像的按钮:

<Button Command="{Binding Model.ZoomOnImage}">
    <Image Source="{Binding Model.ImageSource}" Stretch="Uniform" />
</Button>

在我的模型类中,我有这个命令:

private ICommand _zoomOnImage;
public ICommand ZoomOnImage
{
    get
    {
        if (_zoomOnImage == null)
            _zoomOnImage = new RelayCommand(Zoom, CanZoom);
        return _zoomOnImage;
    }
}
private void Zoom() {...}
private bool CanZoom() {...}

当用户点击按钮时,我想要点击 [X; Y] 坐标(执行Zoom(int X, int Y))。如何修改我的代码来实现这一点?

【问题讨论】:

  • 您可以使用事件处理程序来处理单击事件,然后使用鼠标位置(X 和 Y)调用您的命令。这将保持它 MvvM :-)
  • @Diado 我查看了您的链接,但我不确定它是否尊重 MvvM。没有办法在视图中提供 X,Y 吗?
  • 如果您查看来自 Diado 链接的 this answer,您可以在那里获取鼠标坐标,理想情况下,您会创建一个自定义类来保存这些值,因此当您将其传递到您的 VM 时它不依赖于PresentationFramework.dll。 HTH

标签: c# wpf button command


【解决方案1】:

如果您愿意,可以使用自定义按钮或创建行为。还将属性添加到您的视图模型中public Point MousePosition{get;set;}

<local:CustomButton  Command="{Binding Model.ZoomOnImage}" MousePosition="{Binding MousePosition}">
    <Image Source="{Binding Model.ImageSource}" Stretch="Uniform" />
</local:CustomButton>

public class CustomButton : Button
{

    public Point MousePosition
    {
        get { return (Point)GetValue(MousePositionProperty); }
        set { SetValue(MousePositionProperty, value); }
    }
    // Using a DependencyProperty as the backing store for MousePosition.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MousePositionProperty = DependencyProperty.Register("MousePosition", typeof(Point), typeof(CustomButton), new FrameworkPropertyMetadata(new Point(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    protected override void OnClick()
    {
        base.OnClick();
        MousePosition = Mouse.GetPosition(this);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多