WPF中鼠标悬停操作的事件

10

我希望能够处理网格的鼠标悬停和鼠标移出事件。WPF是否有这方面的事件? 注意:我不想在我的样式中使用IsMouseOver属性。我已经尝试使用MouseEnter和MouseLeave方法,但效果不佳。


“我不想在我的样式中使用IsMouseOver属性”:为什么?你到底想做什么? - Thomas Levesque
为什么MouseEnter和MouseLeave不起作用? - Bubblewrap
4个回答

11

你可以使用EventTriggers在XAML中捕获MouseEnter和MouseLeave事件。

这里有一个简单的例子,在Grid中更改StackPanel的背景:

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

8

一个 WPF Grid 控件支持 MouseEnterMouseLeave 事件。您应该能够为两者都挂钩事件处理程序。


2
更简单的方法: 您可以实现两个事件PointerMoved和PointerExited。这对我很有效。

2

MouseEnter和MouseLeave事件可以被处理,您可以检查您的代码设置e.handled = false;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接