Sanath Shetty
Sanath Shetty

Reputation: 484

How do I Convert the Animation of XAML Code to C#

How can I convert this piece of XAML code to code-behind in C# as my from and to value changes dynamically?

XAML

<Window.Triggers>
    <EventTrigger RoutedEvent="Window.Loaded">
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation BeginTime="00:00:00"    
                            From="200"
                            To="500"
                            Storyboard.TargetProperty="(Window.Top)"    
                            AccelerationRatio=".1"   
                            Duration="0:0:.2" />
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>

Upvotes: 3

Views: 446

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81233

You don't need Storyboard from code behind, that can be done only with DoubleAnimation.

public MainWindow()
{
    InitializeComponent();
    Loaded += (s, e) =>
       {
          DoubleAnimation animation = new DoubleAnimation(200, 500, 
                                          TimeSpan.FromSeconds(0.2));
          animation.AccelerationRatio = 0.1;
          BeginAnimation(Window.TopProperty, animation);
       };
}

Upvotes: 4

Anatoliy Nikolaev
Anatoliy Nikolaev

Reputation: 22702

Try this:

XAML

<Window x:Class="CreateAnimationinCodeHelp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Name="MyWindow" Loaded="Window_Loaded"
        Title="MainWindow" Height="350" Width="525">

    <Grid>
        <Label Background="AliceBlue" Content="Test" />
    </Grid>
</Window>

Code-behind

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Storyboard sb = new Storyboard();

        DoubleAnimation doubleAnimation = new DoubleAnimation();
        doubleAnimation.From = 200;
        doubleAnimation.To = 500;
        doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.2));
        doubleAnimation.AccelerationRatio = 0.1;

        Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Window.Top)"));
        sb.Children.Add(doubleAnimation);

        MyWindow.BeginStoryboard(sb);
    }
}

Upvotes: 1

Related Questions