WPF: Image click event

巧了我就是萌 提交于 2020-01-12 08:49:52

问题


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.


回答1:


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 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.

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 MouseUp event, again with a tolerance value.




回答2:


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.



来源:https://stackoverflow.com/questions/2646929/wpf-image-click-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!