如何在xaml中声明一个故事板并从代码中运行它

sae*_*ati 4 c# wpf xaml

我想在点击按钮时增加当前窗口高度.

我用这个代码:

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); 
        }
Run Code Online (Sandbox Code Playgroud)

但我想在xaml中声明我的故事板并从代码中运行它.

但我不知道这是怎么回事?

Eli*_*bel 11

您可以将其放在资源字典中并从代码中引用它.或者,您可以使用事件触发器在XAML中启动Storyboard:

<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>
Run Code Online (Sandbox Code Playgroud)

从代码开始:

((Storyboard)this.Resources["TheStoryboard"]).Begin(this);
Run Code Online (Sandbox Code Playgroud)

从XAML开始:

<UserControl.Triggers>
    <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="TheButton">
        <BeginStoryboard Storyboard="{StaticResource TheStoryboard}"/>
    </EventTrigger>
</UserControl.Triggers>
Run Code Online (Sandbox Code Playgroud)

为按钮分配名称的位置:

 <Button Name="TheButton" Content="Start" />
Run Code Online (Sandbox Code Playgroud)


Pat*_*man 6

  1. 将故事板声明为窗口中的资源.
  2. 给它一把钥匙.

    <Window.Resources>
        <Storyboard x:Key="test">
             ...
        </Storyboard>
    </Window.Resources>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 找到资源:

    Storyboard sb = this.FindResource("test") as Storyboard;
    
    Run Code Online (Sandbox Code Playgroud)
  4. 用它:

    sb.Begin();
    
    Run Code Online (Sandbox Code Playgroud)