#665 – Reacting to MouseEnter / MouseLeave Events

If there’s some action that you want to take when a user hovers over a control, you can add handlers for the MouseEnter and MouseLeave events.

For example, let’s say that you want to change a Button’s text when the user hovers over the button.  You could define handlers for the MouseEnter and MouseLeave events in XAML:

    <StackPanel Margin="20" >
        <Button Content="Click Me" HorizontalAlignment="Center" Padding="10,5"
                MouseEnter="Button_MouseEnter_1" MouseLeave="Button_MouseLeave_1"/>
    </StackPanel>

Then, in your handlers, you could set (or restore) the Button’s Content property.

        private void Button_MouseEnter_1(object sender, MouseEventArgs e)
        {
            ((Button)sender).Content = "CLICK Me";
        }

        private void Button_MouseLeave_1(object sender, MouseEventArgs e)
        {
            ((Button)sender).Content = "Click Me";
        }



We’ll see next time that there’s a much easier way to do this, using a trigger.

Advertisement

#664 – MouseEnter and MouseLeave Events

An UIElement will fire a MouseEnter event when its IsMouseOver property becomes true.  It will fire a MouseLeave event when its IsMouseOver property becomes false.

These are both direct events, i.e. they don’t bubble or tunnel, but fire only for the UIElement whose IsMouseOver property is changing.

Suppose that we have a Button contained in a StackPanel that is in a Window.

If we move the mouse into the area of the Window that is not covered by the StackPanel, the MouseEnter for the Window will fire.

If we then move into the StackPanel, we’ll get a MouseEnter for the StackPanel, but we will not get a MouseLeave event for the Window–because the pointer is still located in the Window.

 

Moving over the Button fires its MouseEnter event.

 

Moving out of the Button along its top edge triggers MouseLeave events for the Button, the StackPanel, and the Window.