WPF: image click event

I can only find the MouseDown event and the MouseUp event on the image in WPF. This causes some problem if I make MouseDown on some image by moving the mouse, and the MouseUp event occurs on another image. Is there any other event that I can use to solve this problem. as a MouseClick Event for Button element.

+4
source share
2 answers

If you really have to use an image, then there are a few things you can do to test the "click".

  • Check the time between two events. If it is less than your threshold, then treat with the mouse as a click. You will need to save the time of the mouse event.

  • Verify that the sender value of both events is the same. Again you will need to save the sender mouse event.

You can also verify that the left button has been pressed and released.

Combination of 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 } } } 

In fact, you can do the third thing: check the position of the mouse.

  private Point downPosition; 

save position:

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

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

+9
source

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

+4
source

Source: https://habr.com/ru/post/1307052/


All Articles