Stop WPF animation, storyboard begin in xaml but stopping it in codebehind?

Define the storyboard as a static resource,

<MyControl.Resources>
                        <Storyboard Key="MovingServer" Storyboard.TargetName="ImageMove" RepeatBehavior="Forever" >
                            <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:2" From="30" To="300" BeginTime="0:0:0" />
                            <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:5" From="300" To="300" BeginTime="0:0:5" />
                            <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:2" From="300" To="600" BeginTime="0:0:7" />
                            <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:2" From="1" To="0" BeginTime="0:0:7" />
                        </Storyboard>
</MyControl.Resources>

and reference it from your backend code as follows :

StoryBoard board = (StoryBoard)this.FindResource("MovingServer");
board.stop();

start the animation from the 'click' event of the button (i don't know if you defined in xaml, but here's how it would be done if you did)

<Button x:Name="ScanButton" onClick="Scanbutton_Click"></button>


protected void Scanbutton_Click(object Sender, EventArgs e)
{
    StoryBoard board = (StoryBoard)this.FindResource("MovingServer");
    board.start();
}

I solve the problem with using the Stop() method of Storyboard class like this

myStoryBoard.Stop(this.LayoutRoot);

with this solution you don't have to declare Storyboard at the resource.

Tags:

C#

Wpf

Xaml