Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start Storyboard from C# code

Tags:

c#

animation

wpf

I am trying to call a storyboard declared in xaml code from C#:

<Storyboard x:Key="BotRotation"  Duration="00:00:4" RepeatBehavior="Forever" >
            <DoubleAnimation BeginTime="0:0:0"
            Storyboard.TargetName="imageRotateTransformm"
            Storyboard.TargetProperty="ScaleX"
            From="1" To="-1"
            Duration="0:0:2"   
            />
            <DoubleAnimation
            BeginTime="0:0:2"
            Storyboard.TargetName="imageRotateTransformm"
            Storyboard.TargetProperty="ScaleX"
            From="-1" To="1"
            Duration="0:0:2"  
            />
        </Storyboard>
</Window.Resources>

This storyboard should modify the ScaleX property of image. Image Declaration:

<Image Name="uiRobotIcon" Height="64" Width="64" Source="/YoutubeTelegramAudio;component/imgs/ic_robot.png" RenderTransformOrigin="0.5,0.5">
            <Image.RenderTransform>
                <TransformGroup>
                    <ScaleTransform ScaleY="1" ScaleX="1" x:Name="imageRotateTransformm" />
                    <SkewTransform AngleY="0" AngleX="0" />
                    <RotateTransform Angle="0" />
                    <TranslateTransform/>
                </TransformGroup>
            </Image.RenderTransform>
        </Image>

Then, i want to start this animation from C# when i click another button. Thanks.

like image 890
Antonio Avatar asked Sep 12 '25 09:09

Antonio


1 Answers

That's very easy. Just find the Resource, cast it to a Storyboard and then call its Begin() method:

Storyboard sb = (<YourNamespace>.Properties.Resources["BotRotation"] as Storyboard);
sb.Begin();

Put the above code in some event handler and it should work fine.

But:

It also matters where in the application you declare the Storyboard. If it is in the App.xaml, then no worries but anywhere else, and it might be unaccessible. But I think the Window.Resources tag can also contain accessible resources. I can't test it right now :)

like image 178
Fᴀʀʜᴀɴ Aɴᴀᴍ Avatar answered Sep 13 '25 23:09

Fᴀʀʜᴀɴ Aɴᴀᴍ