Search code examples
c#wpfvb.netanimationstoryboard

Determine if storyboard is active if myStoryboard havent begun yet?


1- Copy and paste following code into MainWindow.xaml file.

<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- Copy and paste following code into code behind file.

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- Run this project, wait two seconds and see this error: https://prnt.sc/n08a3j

Error message:

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

So, how can I solve that error?

How to determine if storyboard is active if myStoryboard havent begun yet?


Solution

  • There's 2 problems here, the first one is that your code does not call the Begin method unless the text is changed. The Begin method however determines if the Storyboard is controllable.

    In order to call GetCurrentState it needs that controllable flag.

    So make sure you call Begin first (I don't know what your application is supposed to do upon the initial text but did you mean to use the NOT operator in If NOT TextBox1.Text = "Hello" Then?

    Second, you want to pass in the containingObject to the GetCurrentState:

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

    I've applied the 2 changes and the app is able to run the animation without an exception.