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