Simple hover effect in XAML?

此生再无相见时 提交于 2019-12-10 23:33:33

问题


So, I was recently frustrated with a challenge to copy this effect:

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

Using the XAML implementation in WinRT.

What is the most condense solution?


回答1:


Okay, so here's my attempt:

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

And this:

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);
}

But, surely there's a better way!




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

"Hover" state in RT is "PointerOver".




回答3:


I think you have to look into Visual States and the VisualStateManager. I think the Button control is the only one having visual states, meaning your visual entity must be defined as a Button (although it doesn't have to function as one). In the bottom of that article, you will find an example.

This SO-question might also be helpful, describing how to extract the control template from an existing button. This will give you a starting point you can modify for your needs.

As for "most condense solution", I'd like to see that as well. The examples I've seen all require 20+ lines of XAML code, which to me doesn't feel very condense...



来源:https://stackoverflow.com/questions/11160715/simple-hover-effect-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!