c# - 为什么 e.Handled = true 不起作用?

标签 c# wpf routed-events

我有以下 XAML

 <StackPanel MouseEnter="StackPanel_MouseEnter" Height="130" Background="Blue">
    <Grid MouseEnter="Grid_MouseEnter" Height="60" Background="Red" >
       <Button MouseEnter="Button_MouseEnter" Height="20"/>
    </Grid>
 </StackPanel>

在后面的代码中我正在这样做

private void StackPanel_MouseEnter(object sender, MouseEventArgs e)
{

}

private void Grid_MouseEnter(object sender, MouseEventArgs e)
{
    e.Handled = true;
}

private void Button_MouseEnter(object sender, MouseEventArgs e)
{   
    e.Handled = true;
}

现在,即使我将鼠标移到 Button 上并设置 e.Handled = trueGridStackPanel< 的事件 分别被调用。为什么?我应该怎么做才能阻止路由事件冒泡?

最佳答案

MouseEnter 事件不是冒泡事件,它是直接事件(类似于经典的 CLR 事件)。来自documentation :

You can define multiple MouseEnter events for objects in XAML content. However, if a child object and its parent object both define a MouseEnter event, the parent object's MouseEnter event occurs before the child object's MouseEnter event. This is not a case of a bubbling event; it indicates only that the mouse (or stylus) has entered both objects, potentially at different times depending on the layout and the composition of the visual tree.

所以你不能阻止它被 parent 解雇。您可以使用 IsMouseDirectlyOver属性来查看鼠标实际上是否仅在给定元素上。

关于c# - 为什么 e.Handled = true 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6296836/

相关文章:

c# - 触发 ListView 的 IsSelected 属性(初学者)

c# - 如何从用户控件引发自定义路由事件?

c# - 自定义附加事件的处理程序

WPF 按钮单击路由事件

c# - 从 ASP.NET Core 中的 WebSocket 请求返回什么 IActionResult?

wpf - WPF 中的多语言

c# - 检测到冲突的更改。当尝试插入具有相同键的多个实体时可能会发生这种情况

c# - 如何在 RichTextBox 中找到一个 TextRange(在两个 TextPointer 之间)

c# - 抑制 GridViewColumn 上的鼠标悬停效果

c# - 自定义 XmlSerializer 只在 WebApi 中添加命名空间