如果 myStoryboard 还没有开始,确定 Storyboard 是否处于活动状态?

Determine if storyboard is active if myStoryboard havent begun yet?

1- 将以下代码复制并粘贴到 MainWindow.xaml 文件中。

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <Label x:Name="Label1" Height="25" Width="100" Background="Gainsboro"/>
    <TextBox x:Name="TextBox1" Height="25" Width="100" Background="Pink" Text="Hello"/>
</StackPanel>
</Window>

2- 将以下代码复制并粘贴到 code behind 文件中。

Class MainWindow

Private WithEvents myDispatcherTimer As New System.Windows.Threading.DispatcherTimer

Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    AddHandler myDispatcherTimer.Tick, AddressOf myCode_Tick
    myDispatcherTimer.Interval = TimeSpan.FromSeconds(0.5)
    myDispatcherTimer.Start()
End Sub

Private Sub myCode_Tick(ByVal sender As Object, ByVal e As EventArgs)

    Dim myColorAnimation As New Animation.ColorAnimation With {.From = Colors.Transparent, .To = Colors.Red, .Duration = TimeSpan.FromSeconds(0.4), .AutoReverse = True}
    Animation.Storyboard.SetTargetName(element:=myColorAnimation, name:="Label1")
    Animation.Storyboard.SetTargetProperty(element:=myColorAnimation, path:=New PropertyPath("(Label.Background).(SolidColorBrush.Color)"))
    Dim myStoryboard As New Animation.Storyboard
    myStoryboard.Children.Add(myColorAnimation)

    If Not TextBox1.Text = "Hello" Then
        myStoryboard.Begin(containingObject:=Me, isControllable:=True, handoffBehavior:=Animation.HandoffBehavior.SnapshotAndReplace)
    Else
        If myStoryboard.GetCurrentState(containingObject:=Me) = Animation.ClockState.Active Then
            myStoryboard.Stop(containingObject:=Me)
        End If
    End If

End Sub

End Class

3-运行这个项目,等两秒看到这个错误:https://prnt.sc/n08a3j

错误信息:

Cannot perform action because the specified Storyboard was not applied to this object for interactive control

那么,我该如何解决该错误?

如果我的故事板还没有开始,如何判断故事板是否激活?

这里有 2 个问题,第一个是您的代码不会调用 Begin 方法,除非更改文本。然而,Begin 方法确定 Storyboard 是否 可控

为了调用GetCurrentState,它需要可控标志。

所以请务必先调用 Begin(我不知道您的应用程序应该对初始文本执行什么操作,但您的意思是要使用 NOT If NOT TextBox1.Text = "Hello" Then?

中的运算符

其次,您想将 containingObject 传递给 GetCurrentState:

If myStoryboard.GetCurrentState(containingObject:=Me) = Animation.ClockState.Active Then

我已经应用了 2 项更改,并且该应用能够 运行 动画,没有任何异常。