Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how declare a storyboard in xaml and run it from code

Tags:

c#

wpf

xaml

I want to increase current window height when click on button.

I use this code:

private void sendbtn_Click(object sender, RoutedEventArgs e)
        {
            DoubleAnimation myDoubleAnimation = new DoubleAnimation();
            myDoubleAnimation.From = this.Height;
            myDoubleAnimation.To = 500;
            myDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));

            Storyboard myStoryboard = new Storyboard();
            myStoryboard.Children.Add(myDoubleAnimation);
            Storyboard.SetTargetName(myDoubleAnimation, this.Name);
            Storyboard.SetTargetProperty(myDoubleAnimation, new PropertyPath(Window.HeightProperty));

            myStoryboard.Begin(this); 
        }

but I want declare my storyboard in xaml and run it from code.

but I dont know how do this ??

like image 803
saeid ezzati Avatar asked Dec 05 '22 06:12

saeid ezzati


2 Answers

You can put it in a resource dictionary and reference it from code. Alternatively, you could use an event trigger to start the Storyboard in XAML:

<UserControl.Resources>
    <Storyboard x:Key="TheStoryboard">
        <DoubleAnimation Storyboard.TargetProperty="Height"
                         To="500" Duration="0:0:0.5"
                         Storyboard.TargetName="X" /> <!-- no need to specify From -->
    </Storyboard>
</UserControl.Resources>

To start from code:

((Storyboard)this.Resources["TheStoryboard"]).Begin(this);

To start from XAML:

<UserControl.Triggers>
    <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="TheButton">
        <BeginStoryboard Storyboard="{StaticResource TheStoryboard}"/>
    </EventTrigger>
</UserControl.Triggers>

Where the button is assigned the name:

 <Button Name="TheButton" Content="Start" />
like image 185
Eli Arbel Avatar answered Dec 06 '22 20:12

Eli Arbel


  1. Declare the storyboard as resource in your Window.
  2. Give it a key.

    <Window.Resources>
        <Storyboard x:Key="test">
             ...
        </Storyboard>
    </Window.Resources>
    
  3. Find the resource:

    Storyboard sb = this.FindResource("test") as Storyboard;
    
  4. Use it:

    sb.Begin();
    
like image 22
Patrick Hofman Avatar answered Dec 06 '22 19:12

Patrick Hofman