This is the XAML part.
<StackPanel Orientation="Vertical">
<Border Name="myBorder"
BorderBrush="Black"
BorderThickness="2"
Width="100"
Height="100"
MouseEnter="MyBorder_OnMouseEnter"
MouseLeave="MyBorder_OnMouseLeave">
</Border>
<StackPanel Width="150"
Height="150"
Background="Red"
MouseEnter="StackPanel_OnMouseEnter"
MouseLeave="StackPanel_OnMouseLeave"/>
</StackPanel>
Here is the C# part
private void MyBorder_OnMouseEnter(object sender, MouseEventArgs e)
{
Debug.WriteLine("MyBorder_OnMouseEnter");
}
private void MyBorder_OnMouseLeave(object sender, MouseEventArgs e)
{
Debug.WriteLine("MyBorder_OnMouseLeave");
}
private void StackPanel_OnMouseEnter(object sender, MouseEventArgs e)
{
Debug.WriteLine("UIElement_OnMouseEnter");
}
private void StackPanel_OnMouseLeave(object sender, MouseEventArgs e)
{
Debug.WriteLine("UIElement_OnMouseLeave");
}
When I hover over border element MouseEnter, MouseLeave events fire both. When mouse leaves the border MouseEnter, MouseLeave events fire again. With stackpanel it behaves the way I expect. Why is this happening?
Watch this to see the behaviour
>Solution :
If you don’t set the Background property of the Border to a Brush, the unpainted area is considered to belong to the parent element.
If you set the Background to Transparent, the events will get raised as expected:
<Border Name="myBorder"
Background="Transparent"
BorderBrush="Black"
BorderThickness="2"
Width="100"
Height="100"
MouseEnter="MyBorder_OnMouseEnter"
MouseLeave="MyBorder_OnMouseLeave">