Search code examples
c#.netwpfanimationeventtrigger

Creating Storyboard in code behind in WPF


The following code is working fine.

<Window.Triggers>
    <EventTrigger RoutedEvent="Window.Loaded">
        <BeginStoryboard>
            <Storyboard>
                <DoubleAnimation Duration="0:0:.8" Storyboard.TargetProperty="Left" From="1920" To="0" AccelerationRatio=".1"/>
            </Storyboard>
        </BeginStoryboard>
    </EventTrigger>
</Window.Triggers>

But in this From and To values are static. I need to pass the values dynamically based system resolution. So i need it to be created in code behind. Is it possible to do ?

How to convert it to codebehind?


Solution

  • When working in code, you don't need Storyboard really, just animations for basic things, like you show in your question. I made a little sample to show how easy it works.

    This is the complete code behind of the mainwindow:

    namespace WpfCSharpSandbox
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                WidenObject(150, TimeSpan.FromSeconds(1));
            }
    
            private void WidenObject(int newWidth, TimeSpan duration)
            {
                DoubleAnimation animation = new DoubleAnimation(newWidth, duration);
                rctMovingObject.BeginAnimation(Rectangle.WidthProperty, animation);
            }
        }
    }
    

    This is how the XAML looks like:

    <Window x:Class="WpfCSharpSandbox.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Sandbox" Height="350" Width="525">
        <Grid Background="#333333">
            <Rectangle x:Name="rctMovingObject" Fill="LimeGreen" Width="50" Height="50"/>
        </Grid>
    </Window>
    

    Put this in a WPF app and see how it works, experiment with it and try other animations/properties.