Wpf – Event for MouseOver action in WPF

wpf

I want to handle mouse over and mouse out events for a grid. Does WPF have events for this.
Note: I dont want to use IsMouseOver property in my style.
i have used MouseEnter and MouseLeave method but without much success.

Best Answer

You can use EventTriggers to capture MouseEnter and MouseLeave events in XAML.

Here is a simple example that changes the background of a StackPanel in a Grid:

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition/>
    <RowDefinition/>
  </Grid.RowDefinitions>
  <StackPanel Grid.Row="1" Background="Blue">
    <StackPanel.Style>
      <Style>
        <Style.Triggers>
          <EventTrigger RoutedEvent="StackPanel.MouseEnter">
            <EventTrigger.Actions>
              <BeginStoryboard>
                <Storyboard>
                  <ColorAnimation 
                      AutoReverse="False" 
                      Duration="0:0:1" 
                      From="Blue" To="Red"
                      AccelerationRatio="1" 
                      Storyboard.TargetProperty="(StackPanel.Background).(SolidColorBrush.Color)"
                      FillBehavior="HoldEnd">
                  </ColorAnimation>
                </Storyboard>
              </BeginStoryboard>
            </EventTrigger.Actions>
          </EventTrigger>
          <EventTrigger RoutedEvent="StackPanel.MouseLeave">
            <EventTrigger.Actions>
              <BeginStoryboard>
                <Storyboard>
                  <ColorAnimation 
                      AutoReverse="False" 
                      Duration="0:0:1" 
                      From="Red" To="Blue"
                      AccelerationRatio="1" 
                      Storyboard.TargetProperty="(StackPanel.Background).(SolidColorBrush.Color)"
                      FillBehavior="HoldEnd">
                  </ColorAnimation>
                </Storyboard>
              </BeginStoryboard>
            </EventTrigger.Actions>
          </EventTrigger>
        </Style.Triggers>
      </Style>
    </StackPanel.Style>
  </StackPanel>
</Grid>