Animate button background color in XAML

天涯浪子 提交于 2020-01-02 08:02:37

问题


I new to WPF and XAML, so I have ResourceDictionary (one button for now):

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style x:Key="ButtonProduct" TargetType="Button">
        <Setter Property="SnapsToDevicePixels" Value="true"/>
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Name="Border"  
                            CornerRadius="0" 
                            BorderThickness="0"
                            Focusable="False"
                            BorderBrush="Transparent" Background="White">
                        <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter  Property="Background" Value="#52b0ca"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

On hover the color of the button changes, but how can I make change in fade in and out, for smooth transition of the color?


回答1:


You can use EventTrigger to start ColorAnimation on MouseEnter and MouseLeave:

<ControlTemplate TargetType="{x:Type Button}">
   <Border Name="Border" CornerRadius="0" BorderThickness="0" Focusable="False" BorderBrush="Transparent" Background="White">
      <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
   </Border>
   <ControlTemplate.Triggers>
      <EventTrigger RoutedEvent="MouseEnter">
         <BeginStoryboard>
            <Storyboard>
               <ColorAnimation From="White" To="#52b0ca" Duration="0:0:1" Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color"/>
            </Storyboard>
         </BeginStoryboard>
      </EventTrigger>
      <EventTrigger RoutedEvent="MouseLeave">
         <BeginStoryboard>
            <Storyboard>
               <ColorAnimation From="#52b0ca" To="White" Duration="0:0:1" Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color"/>
            </Storyboard>
         </BeginStoryboard>
      </EventTrigger>
   </ControlTemplate.Triggers>
</ControlTemplate>


来源:https://stackoverflow.com/questions/21969016/animate-button-background-color-in-xaml

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