如何在xaml中声明故事板并从代码中运行它
本文关键字:代码 运行 故事 xaml 声明 | 更新日期: 2023-09-27 18:03:11
我想在点击按钮时增加当前窗口的高度。
我使用以下代码:
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);
}
但是我想在xaml中声明storyboard然后从代码中运行
但是我不知道怎么做??
您可以将其放入资源字典中并从代码中引用它。或者,您可以使用事件触发器在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>
从代码开始:
((Storyboard)this.Resources["TheStoryboard"]).Begin(this);
从XAML:
<UserControl.Triggers>
<EventTrigger RoutedEvent="ButtonBase.Click" SourceName="TheButton">
<BeginStoryboard Storyboard="{StaticResource TheStoryboard}"/>
</EventTrigger>
</UserControl.Triggers>
按钮指定的名称:
<Button Name="TheButton" Content="Start" />
- 在你的窗口中声明故事板作为资源。
-
给它一个键
<Window.Resources> <Storyboard x:Key="test"> ... </Storyboard> </Window.Resources>
-
查找资源:
Storyboard sb = this.FindResource("test") as Storyboard;
-
使用它:
sb.Begin();
Storyboard sb = (Storyboard)btnPause.FindResource("PauseStoryboard");
//to start
sb.Begin(btnPause, true);
//to stop
sb.Stop(btnPause);
<Button x:Name="btnPause" Width="28" Background="LightCyan" Click="btnPause_Click">
<Image Source="Images'pause.png"></Image>
<Button.Resources>
<Storyboard x:Key="PauseStoryboard">
<ColorAnimation To="Yellow" Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)" Duration="0:0:1" RepeatBehavior="Forever" AutoReverse="True"/>
</Storyboard>
</Button.Resources>
</Button>