C# WPF - Canvas 即使鼠标移到子控件上也会触发 MouseMove 事件

C# WPF - Canvas MouseMove event firing even when mouse moves over child control

如何使 Canvas MouseMove 事件仅在我的鼠标悬停在 CanvasCanvas 上时触发?

我有一个 TextBox 作为 Canvas 的子项,当我的鼠标移到 TextBox 上时它仍然会触发,我希望这不会发生,它应该例如,只有当鼠标移过 Canvas background/blank space 时才会触发。

您必须在 canvas PreviewMouseMove 上收听该事件的预览版本并设置 e.Handled = true。 看看这个 url https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/routed-events-overview

How to make it so the canvas MouseMove event only fires if my mouse is over the Canvas and the Canvas only?

您无法阻止事件被触发,但您可以检查鼠标是否直接位于事件处理程序中的 Canvas 区域上方,如果不是,则什么都不做:

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    if (Mouse.DirectlyOver == sender)
    {
        //your code...
    }
    //else, i.e. when the mouse moves over the TextBox or another child element, do nothing
}