编程语言
首页 > 编程语言> > c# – XAML中的动画按钮背景颜色

c# – XAML中的动画按钮背景颜色

作者:互联网

我是WPF和XAML的新手,所以我有ResourceDictionary(现在只有一个按钮):

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

在悬停时,按钮的颜色会发生变化,但是如何在淡入和淡出时进行更改,以便平滑过渡颜色?

解决方法:

您可以使用EventTrigger在MouseEnter和MouseLeave上启动ColorAnimation:

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

标签:c,wpf,xaml,resourcedictionary,wpf-animation
来源: https://codeday.me/bug/20190718/1491407.html