Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate button background color in XAML

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?

like image 900
Dim Avatar asked Dec 12 '22 07:12

Dim


1 Answers

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>
like image 130
dkozl Avatar answered Dec 28 '22 02:12

dkozl