WPF: Image click event

mouseevent, wpf

Solution

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

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.

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.

Problem

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.

Original source