Shalvin Interests

Thursday, April 21, 2011

WPF Animation

Animation in code

using System.Windows.Media.Animation;
private void button1_Click(object sender, RoutedEventArgs e)
{
    DoubleAnimation widthAnimation = new DoubleAnimation();
    widthAnimation.To = cmdGrow.Width * 2;
    widthAnimation.Duration = TimeSpan.FromSeconds(5);

    DoubleAnimation heightAnimation = new DoubleAnimation();
    heightAnimation.To = cmdGrow.Height * 2;
    heightAnimation.Duration = TimeSpan.FromSeconds(5);

    cmdGrow.BeginAnimation(Button.WidthProperty, widthAnimation);
    cmdGrow.BeginAnimation(Button.HeightProperty, heightAnimation);
}

Animation with Styles
<Window x:Class="XamlAnimationShalvin.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
 <Window.Resources>

  <Style x:Key="GrowButtonWindowStyle">
   <Style.Triggers>
    <Trigger Property="Button.IsPressed" Value="True">
     <Trigger.EnterActions>
      <BeginStoryboard>
       <Storyboard>
        <DoubleAnimation Storyboard.TargetProperty="Width"
          To="250" Duration="0:0:5"></DoubleAnimation>
       </Storyboard>
      </BeginStoryboard>
     </Trigger.EnterActions>
    </Trigger>
   </Style.Triggers>
  </Style>

 </Window.Resources>
   <Button Padding="10" Name="cmdGrow" Height="40" Width="160" Style="{StaticResource GrowButtonWindowStyle}"
          HorizontalAlignment="Center" VerticalAlignment="Center">
        Click and Make Me Grow
  </Button>
</Window>