In this example, we will create a simple storyboard animation for a Button control in a WPF application. We will define the storyboard in the .cs file and use it in the .xaml file inside the Style of the ControlTemplate.
- Create the .cs file:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace WpfApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CreateStoryboard();
}
private void CreateStoryboard()
{
DoubleAnimation buttonAnimation = new DoubleAnimation
{
From = 1,
To = 0.5,
Duration = new Duration(TimeSpan.FromSeconds(0.5)),
AutoReverse = true
};
Storyboard.SetTargetProperty(buttonAnimation, new PropertyPath("Opacity"));
ButtonStoryboard.Children.Add(buttonAnimation);
}
}
}
- Create the .xaml file:
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="300">
<Window.Resources>
<Storyboard x:Key="ButtonStoryboard" x:Name="ButtonStoryboard" />
<Style x:Key="AnimatedButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard Storyboard="{StaticResource ButtonStoryboard}" />
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button x:Name="MyButton" Content="Click Me" Width="100" Height="30" HorizontalAlignment="Center" VerticalAlignment="Center" Style="{StaticResource AnimatedButtonStyle}" />
</Grid>
</Window>
In this example, we have created a simple storyboard animation that changes the opacity of a Button control when the mouse pointer enters the button. The storyboard is defined in the .cs file and used in the .xaml file inside the Style of the ControlTemplate.