Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have following 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>

In code behind I am doing this

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;
}

Now even if I move mouse over Button and set e.Handled = true, the events of Grid and StackPanel are called respectively. Why? What should I do to stop routed event from bubbling up?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
292 views
Welcome To Ask or Share your Answers For Others

1 Answer

The MouseEnter event is not a bubbling event, it is a direct event (like classic CLR events). From the 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.

So you can't prevent it from being fired on the parents. You can use the IsMouseDirectlyOver property to see if the mouse is in fact only over the given element though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...