在XAML中使按钮背景颜色动画化

4

我刚开始学习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>

当鼠标悬停在按钮上时,按钮的颜色会发生变化,但如何使颜色渐变以实现平滑的过渡呢?


更明确地说,在那个 ResourceDictionary 中有一个名为 Style 的按钮。 - superjos
1个回答

14

您可以使用EventTriggerMouseEnterMouseLeave时启动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>

如果你正在为一个触摸屏亭开发程序,而且没有鼠标怎么办?我只能使用点击事件... - Shawn J. Molloy
1
你可以使用“TouchDown”和“TouchUp”事件。 - dkozl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接