WPF:图片点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2646929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:41:03  来源:igfitidea点击:

WPF: Image click event

wpfmouseevent

提问by user279244

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.

我只能在 WPF 中的图像上找到 MouseDown 事件和 MouseUp 事件。如果我在某些图像上执行 MouseDown,移动鼠标和 MouseUp 事件发生在其他图像上,这会导致一些问题。有没有其他事件可以用来解决这个问题。像 Button 元素的 MouseClick 事件。

回答by ChrisF

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

如果您真的必须使用图像,那么您可以执行一些操作来检查“点击”。

  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.

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

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

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

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

您可能还想检查是否按下并释放了左侧按钮。

Combining the two:

两者结合:

    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;

save the position:

保存位置:

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

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

然后在MouseUp事件中检查它,再次使用公差值。

回答by Wallstreet Programmer

Are you sure that you want just an image or do you actually want a button with an image as content? A button with an image will have the click event.

你确定你只想要一个图像还是你真的想要一个带有图像作为内容的按钮?带有图像的按钮将具有单击事件。