WPF:图片点击事件 [英] WPF: Image click event

查看:2572
本文介绍了WPF:图片点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只能在WPF中的图像上找到MouseDown事件和MouseUp事件. 如果我在某些图像上执行MouseDown,移动鼠标,而在其他图像上发生MouseUp事件,则会引起一些问题. 还有其他可以用来解决此问题的事件吗?就像Button元素的MouseClick事件.

I can find only MouseDown Event and MouseUp Event on a image in WPF. This causes some problem if I do MouseDown on some Image, Move the mouse and MouseUp event happens on some other image. Is there any other event that I can use to solve this problem. like MouseClick Event for Button element.

推荐答案

如果您确实必须使用图片,则可以执行几项操作来检查点击".

If you really must use an image then there's a couple of things you can do to check for a "click".

  1. 检查两个事件之间的时间.如果小于阈值,则将鼠标视为单击.您需要存储鼠标按下事件的时间.

  1. Check the time between the two events. If it's less than your threshold, then treat the mouse up as a click. You'll need to store the time of the mouse down event.

检查两个事件的sender是否相同.同样,您需要存储鼠标按下事件的sender.

Check that the sender of both events is the same. Again you'll need to store the sender of the mouse down event.

您可能还需要检查是否已按下并释放了鼠标左键.

You might also want to check that it's the left button that's been pressed and released.

两者结合:

    private DateTime downTime;
    private object downSender;

    private void Image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            this.downSender = sender;
            this.downTime = DateTime.Now;
        }
    }

    private void Image_MouseUp(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Released &&
            sender == this.downSender)
        {
            TimeSpan timeSinceDown = DateTime.Now - this.downTime;
            if (timeSinceDown.TotalMilliseconds < 500)
            {
                // Do click
            }
        }
    }

实际上您可以做的第三件事是:检查鼠标位置.

There's actually a third thing you can do: Check the mouse position.

    private Point downPosition;

保存位置:

    this.downPosition = e.GetPosition(sender as Image);

然后在MouseUp事件中再次检查它,并带有公差值.

then check it in the MouseUp event, again with a tolerance value.

这篇关于WPF:图片点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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