【问题标题】:Simple hover effect in XAML?XAML 中的简单悬停效果?
【发布时间】:2012-06-25 00:27:34
【问题描述】:

所以,我最近对复制此效果的挑战感到沮丧:

<style>
a:hover {background-color:yellow; }
</style>

在 WinRT 中使用 XAML 实现。

什么是最简洁的解决方案?

【问题讨论】:

    标签: css xaml windows-8 microsoft-metro winrt-xaml


    【解决方案1】:

    好的,这是我的尝试:

    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="VisualStateGroup">
            <VisualState x:Name="Normal"/>
            <VisualState x:Name="Hover">
                <Storyboard>
                    <ColorAnimation To="Yellow" Duration="0"
                        Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" 
                        Storyboard.TargetName="MyTextBox" />
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    
    <Grid x:Name="MyTextBox" Background="White"
            PointerEntered="MyTextBox_PointerEntered" 
            PointerExited="MyTextBox_PointerExited"
            Height="114" Width="537">
    </Grid>
    

    还有这个:

    private void MyTextBox_PointerEntered(object sender, PointerRoutedEventArgs e)
    {
        VisualStateManager.GoToState(this, Hover.Name, false);
    }
    
    private void MyTextBox_PointerExited(object sender, PointerRoutedEventArgs e)
    {
        VisualStateManager.GoToState(this, Normal.Name, false);
    }
    

    但是,肯定有更好的方法!

    【讨论】:

    • 在研究滚动查看器上的悬停情况时遇到了这个问题。有趣的解决方案。 :-)
    【解决方案2】:
    <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal"/>
                    <VisualState x:Name="PointerOver">
                        <Storyboard>
                            <ColorAnimation To="Yellow" Duration="0"
                    Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" 
                    Storyboard.TargetName="MyTextBox" />
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="Pressed"/>
                </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    

    RT中的“Hover”状态为“PointerOver”。

    【讨论】:

      【解决方案3】:

      我认为您必须研究 Visual States 和 VisualStateManager。我认为 Button 控件是唯一具有视觉状态的控件,这意味着您的视觉实体必须定义为一个 Button(尽管它不必作为一个)。在该文章的底部,您会找到一个示例。

      This SO-question 也可能会有所帮助,描述如何从现有按钮中提取控件模板。这将为您提供一个起点,您可以根据自己的需要进行修改。

      至于“最简洁的解决方案”,我也想看看。我见过的例子都需要20多行XAML代码,我觉得不是很紧凑……

      【讨论】:

      • 不,我不认为 Button 是 VisualStates 的唯一控件。如果你拉起网格模板,它们会在主网格上使用 VisualStateManager 来控制 FullScreenLandscape、Snapped、Portrait 等之间的转换。
      猜你喜欢
      • 2011-08-30
      • 1970-01-01
      • 2014-01-17
      • 2016-11-27
      • 2012-06-05
      • 1970-01-01
      • 2018-12-01
      • 2014-03-29
      • 2021-11-12
      相关资源
      最近更新 更多