Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird MouseEnter, MouseLeave behaviour of Border in WPF

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading