【问题标题】:Event for MouseOver action in WPFWPF 中 MouseOver 动作的事件
【发布时间】:2010-09-17 09:20:54
【问题描述】:

我想为网格处理鼠标悬停和鼠标移出事件。 WPF 是否有这方面的事件。 注意:我不想在我的风格中使用 IsMouseOver 属性。 我已经使用了 MouseEnter 和 MouseLeave 方法,但没有太大的成功。

【问题讨论】:

  • “我不想在我的风格中使用 IsMouseOver 属性”:为什么?你到底想做什么?
  • 为什么 MouseEnter 和 MouseLeave 不适合你?

标签: wpf


【解决方案1】:

您可以使用 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>

【讨论】:

    【解决方案2】:

    WPF 网格控件同时支持MouseEnterMouseLeave 事件。您应该能够为两者连接事件处理程序。

    【讨论】:

      【解决方案3】:

      更简单: 您可以实现两个事件 PointerMoved 和 PointerExited。它对我有用。

      【讨论】:

        【解决方案4】:

        MouseEnter 和 MouseLeave 事件可能会被处理,你可以检查你的代码集 e.handled = false;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-01-26
          • 2011-11-16
          • 1970-01-01
          • 2013-01-13
          • 1970-01-01
          • 1970-01-01
          • 2013-05-19
          • 2018-07-19
          相关资源
          最近更新 更多