WPF: Image click event

25,099

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

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

Share:
25,099
user279244
Author by

user279244

Updated on September 30, 2020

Comments

  • user279244
    user279244 almost 4 years

    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.