简体   繁体   中英

How do you distinguish the sender of mouse up event in WPF?

I want to implement a click-like event using preview left button down and up for controls that do not have a built-in click event. (eg TextBox )

The problem is when the mouse is moved outside of the control PreviewMouseLeftButtonUp event is still fired as if the control sent it.

  1. Mouse down inside of the control. (let's say control A)
  2. User moves the mouse outside of control A while pushing the left button.
  3. User releases the mouse outside of control A.

Since the pointer of the mouse is not in control A, the sender of PreviewMouseLeftButtonUp must be something else than control A.

What I'm experiencing is the sender always be control A in the situation I describe.

Is this an intended operation? If it is the way it works, how can I distinguish the PreviewMouseLeftButtonUp event that is fired inside of control A from that is fired from outside?

You can get the relative position of cursor from MouseEventArgs and then check if it is inside its event source.

private static bool IsMouseEventInsideElement(MouseEventArgs e)
{
    if (e.OriginalSource is not FrameworkElement element)
        return false;

    var cursorPosition = e.GetPosition(element);

    return (0 <= cursorPosition.X && cursorPosition.X <= element.ActualWidth)
        && (0 <= cursorPosition.Y && cursorPosition.Y <= element.ActualHeight);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM