views:

156

answers:

2

I have a situation where I need to determine if I've reached the end of a Storyboard, and then need to seek to the end of it.

I want to do:

storyboard.Seek(timespan);

However, if timespan is longer than the storyboard's duration, I get an exception. If I look at

storyboard.Duration.TimeSpan

I get an error because the Duration is Automatic. This means I can't do "if( timespan > storyboard.Duration.TimeSpan) ..."

Once I know that the position I'm seeking is past the end of the storyboard, I need to just seek to the end of the storyboard. I could do this with storyboard.Seek(storyboard.Duration.TimeSpan), but again, I can't use Duration because it is Automatic.

It seems like all my problems could be solved if I can force the Duration away from Automatic. Hopefully I'm just missing something simple.

+2  A: 
Egor
Thanks for your answer. Your advice helped me to find a good solution.
grimus
A: 

By looking at the pages linked by Egor, I was able to come up with a good solution. (Marking Egor as answer to make sure he gets credit.)

Setting the Duration on the storyboard is part of the answer, but its not enough. I'm using this storyboard as part of a long running custom control - I can't be guaranteed that a re-styled version of the custom control will have the storyboard's duration set.

To get around this problem, I first check to see if the duration is available. If its not, I SkipToFill() to the end, and use GetCurrentTime() to figure out what the end of the length of the storyboard is.

Here's my complete solution:

public void UpdateControl()
{
    if (!App.IsDesignTime() && storyboard != null)
    {
        TimeSpan begin = DateTime.UtcNow - OriginTime.ToUniversalTime();
        TimeSpan end;

        // If Storyboard.Duration is set, use it to set the animation to its correct position.
        // If it isn't set, attempt to set by seeking to the end of the animation.
        if (storyboard.Duration.HasTimeSpan)
            end = storyboard.Duration.TimeSpan;
        else
        {
            storyboard.SkipToFill();
            end = storyboard.GetCurrentTime();
        }

        if (begin > end)
            begin = end;

        storyboard.Begin();
        storyboard.Seek(begin);
    }
}
grimus