Search code examples
wpfsilverlightstoryboard

Port Silverlight Storyboard to WPF


Trying to port to WPF some behavior from an old Silverlight application that allowed users to configure their view by moving/minimizing/maximizing various UserControls. Several StoryBoards were declared in UserControl.Resources and later accessed from code via their x:Name.

<Storyboard x:Name="MaximizeStoryboard" Completed="MaximizeStoryboard_Completed" Storyboard.TargetName="WholeControl">
            <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetProperty="(FrameworkElement.Width)">
                <SplineDoubleKeyFrame x:Name="MaximizeWidth" KeyTime="00:00:00.3000000" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
...

In WPF, after changing x:Name to x:Key, I can access the Storyboard via:

Storyboard maximizeStoryboard = (Storyboard)Resources["MaximizeStoryboard"];

Previously used

MaximizeWidth.Value = Container.Contents.ActualWidth;

to set the restore width (and other values) from code, before beginning the animation. That doesn't work in WPF. What is the proper way to get access so those values can be set from code?


Solution

  • One of the possible way can be go through the children of Storyboard, find DoubleAnimationUsingKeyFrames child and then get the first KeyFrame.

    Storyboard maximizeStoryboard = (Storyboard)Resources["MaximizeStoryboard"];
    var doubleAnimationUsingKeyFrames = maximizeStoryboard.Children.OfType<DoubleAnimationUsingKeyFrames>().FirstOrDefault();
    if (doubleAnimationUsingKeyFrames != null)
    {
        if (doubleAnimationUsingKeyFrames.KeyFrames.Count > 0)
        {
            var keyFrame = doubleAnimationUsingKeyFrames.KeyFrames[0] as SplineDoubleKeyFrame;
            if(keyFrame !=null)
            {
                keyFrame.Value = Container.Contents.ActualWidth;
            }
        }
    }