[英]How to control a storyboard animation from C# and XAML
在.net 上有很多关于此的问题,但在阅读它们以及 animation 控件上的 MS 文档之后,我无法从 C# 代码中的 XAML 事件触发器模仿 storyboard 控件。
在这个 XAML 文件中,我有一个正在旋转的 canvas。 我想为旋转添加交互性,
<Window x:Class="GraphicsBook.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:k="clr-namespace:GraphicsBook;assembly=Testbed2D"
Title="2D Testbed"
KeyDown="KeyDownHandler"
Height="600"
Width="600" >
<DockPanel LastChildFill="True">
<StackPanel x:Name="stack" DockPanel.Dock ="Top" Orientation="Vertical" Background="#ECE9D8">
<Button Name="StartAnimationClick">Start animation</Button>
<Button Name="StopAnimationClick" Click="stopAnimationClick">Stop animation</Button>
<Canvas x:Name="Grid">
<Canvas.RenderTransform>
<TransformGroup>
<RotateTransform x:Name="CanvasRotation" CenterX="300" CenterY="300" Angle="0"/>
</TransformGroup>
</Canvas.RenderTransform>
</Canvas>
<StackPanel.Triggers>
<EventTrigger RoutedEvent="Button.Click" SourceName="StartAnimationClick">
<BeginStoryboard Name="GridRotationStoryboard">
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="CanvasRotation"
Storyboard.TargetProperty="Angle"
From="0.0" To="360.0"
Duration="00:00:10.00" RepeatBehavior="Forever"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<!--<EventTrigger RoutedEvent="Button.Click" SourceName="StopAnimationClick">
<StopStoryboard BeginStoryboardName="GridRotationStoryboard"/>
</EventTrigger>-->
</StackPanel.Triggers>
</StackPanel>
</DockPanel>
</Window>
评论的事件触发器,
<!--<EventTrigger RoutedEvent="Button.Click" SourceName="StopAnimationClick">
<StopStoryboard BeginStoryboardName="GridRotationStoryboard"/>
</EventTrigger>-->
确实按预期工作,也就是说,如果我单击按钮,animation 将停止。 但是,上面的 XAML 版本试图在 C# 中复制此功能,但这不起作用。 点击处理程序看起来像这样,
private void stopAnimationClick(object sender, RoutedEventArgs e)
{
Debug.Print("Stop animation");
// ???
}
我无法控制 animation object 在???
,无论我尝试使用什么技术来处理它。 我一定是以某种方式错误地连接了这些部件,但我看不出有什么问题。
您可以通过使用第二个参数null
调用BeginAnimation
来模拟EventTrigger
的作用:
private void stopAnimationClick(object sender, RoutedEventArgs e)
{
CanvasRotation.BeginAnimation(RotateTransform.AngleProperty, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.