我已经阅读了十几篇关于如何暂停和恢复WPF故事板的文章,但我无法让它发挥作用。 这是我的问题:我有一个带有故事板的用户控件。故事板看起来像这样:
<UserControl.Resources>
<Storyboard x:Key="TheStoryboard" RepeatBehavior="Forever">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)" Storyboard.TargetName="Arc1">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:2" Value="90"/>
<EasingDoubleKeyFrame KeyTime="0:0:4" Value="180"/>
<EasingDoubleKeyFrame KeyTime="0:0:6" Value="270"/>
<EasingDoubleKeyFrame KeyTime="0:0:8" Value="360"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
很简单,它永远是一个方舟旋转。 现在在后面的代码中我有一个依赖属性,它绑定到一个布尔值,指示动画何时应该旋转或停止。这触发了一种理论上应暂停或恢复动画的方法。 它看起来像这样:
private void SetStoryBoardActivity(bool play)
{
var storyboard = (Storyboard)this.Resources["TheStoryboard"];
if (play)
{
storyboard.Resume();
}
else
{
storyboard.Pause();
}
}
执行路径按预期进入方法,但是在调用Pause()时动画不会停止;我试过了
storyboard.Stop();
storyboard.Stop(this);
storyboard.Stop(this.Arc1);
storyboard.Freeze();
storyboard.Pause();
storyboard.Pause(this);
storyboard.Pause(this.Arc1);
但似乎没有任何效果。有谁知道我做错了什么?
答案 0 :(得分:1)
所以我的案例中的答案似乎是视觉状态。 我以下列方式管理这项工作: 我将故事板移动到这样一个视觉状态管理器:
<Grid x:Name="LayoutRoot">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Animation">
<VisualState x:Name="On">
<Storyboard RepeatBehavior="Forever">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[2].(RotateTransform.Angle)" Storyboard.TargetName="Arc1">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
<EasingDoubleKeyFrame KeyTime="0:0:2" Value="90"/>
<EasingDoubleKeyFrame KeyTime="0:0:4" Value="180"/>
<EasingDoubleKeyFrame KeyTime="0:0:6" Value="270"/>
<EasingDoubleKeyFrame KeyTime="0:0:8" Value="360"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Off"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ed:Arc x:Name="Arc1" ArcThickness="15" ArcThicknessUnit="Pixel" StartAngle="30" EndAngle="150" Fill="#C0375E77" HorizontalAlignment="Center" Height="200" Width="200" Margin="0,0,0,0" Stretch="None" Stroke="#FF204050" StrokeThickness="2" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5" >
<ed:Arc.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</ed:Arc.RenderTransform>
</ed:Arc>
</Grid>
请注意,可视状态管理器不会放在控件的资源中,而是放在控件的主容器中。 其中ed是:
xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
SetStoryBoardActivity方法变为:
private void SetStoryBoardActivity()
{
VisualStateManager.GoToState(this, this.AnimationActive ? "On" : "Off", true);
}
this.AnimationActive是我的问题中提到的依赖属性。
答案 1 :(得分:0)
如何尝试:
Storyboard storyboard = (Storyboard)this.Resources["TheStoryboard"];
private void BeginStoryBoard()
{
storyboard.begin(this, true);
}
private void SetStoryBoardActivity(bool play)
{
if (play)
{
storyboard.Resume(this);
}
else
{
storyboard.Pause(this);
}
}