C# WPF - Grid MouseUp 由于之前的 Grid 而未触发

C# WPF - Grid MouseUp not firing due to previous Grid

我的内部网格的 MouseUp 事件似乎没有触发,因为来自周围网格的 MouseDown 事件。我有什么办法可以防止这种情况发生?

<Grid HorizontalAlignment="Left" Height="50" VerticalAlignment="Top" Width="525" MouseDown="Grid_MouseDown_1" Background="#00000000">
        <Grid HorizontalAlignment="Left" Height="20" Margin="495,10,0,0" VerticalAlignment="Top" Width="20" Background="#FF000000" MouseEnter="gridBtn_MouseEnter" MouseLeave="gridBtn_MouseLeave" MouseUp="gridBtn"/>             
</Grid>

您永远不会收到第二格的 MouseDown,因此第二格不会收到 MouseUp。为了让 MouseDown 事件传播到 child,您可能需要处理 PreviewMouseDown 才能在事件中获得第一次破解。然后你会执行某种 hit-testing.

无论如何,您的处理程序未被调用的原因可能是由于e.Handled = true

例如:

private void Grid_MouseDown_1(object sender, MouseButtonEventArgs e)
{
    // Uncomment to allow the MouseUp event for the second grid.
    e.Handled = true;
}

我测试了以下内容,没有问题。

    private void gridBtn(object sender, MouseButtonEventArgs e)
    {
        Debug.WriteLine("MouseUp inner grid");
    }

    private void Grid_MouseDown_1(object sender, MouseButtonEventArgs e)
    {
        Debug.WriteLine("MouseDown outer grid");
    }

    private void gridBtn_MouseEnter(object sender, MouseEventArgs e)
    {
        Debug.WriteLine("MouseEnter inner grid");
    }

    private void gridBtn_MouseLeave(object sender, MouseEventArgs e)
    {
        Debug.WriteLine("MouseLeave inner grid");
    }

我只是更改了网格的颜色,以便于我查看。 希望对你有帮助..