Sadeq Shajary
Sadeq Shajary

Reputation: 351

WPF Second Animation (StoryBoard) doesn't work

This is the scenario: I Have a Grid and an Button. the Grid have a Show Boolean property. When user click on button, if Show=false then Grid become Visible. and when Show=true Grid become Collapse. when it's visibility change, I do an animation for grid's Height with StoryBoard.
OK. every thing is fine. when user click the button, Grid appearing with animation. but when click again, the animation doesn't show and just Collapse occurred.
This is my code:

Storyboard growUpStory = new Storyboard();
    Storyboard growDownStory = new Storyboard();

    DoubleAnimation growUp, growDown;

In any method:

    height = Container.DesiredSize.Height;
    growUp = new DoubleAnimation
                {
                    From = 0,
                    To = height > MaxHeight ? MaxHeight : height,
                    Duration = new Duration(TimeSpan.FromSeconds(1)),
                    AutoReverse = false
                };
               
                Container.Visibility = Visibility.Collapsed;

                growDown = new DoubleAnimation
                {
                    From = height > MaxHeight ? MaxHeight : height,
                    To = 0,
                    Duration = new Duration(TimeSpan.FromSeconds(1)),
                    AutoReverse = false
                };

                growUpStory.Children.Add(growUp);
                growDownStory.Children.Add(growDown);

and when I invoke the event:

if (Show)
            {
                Storyboard.SetTarget(growUpStory, Container);
                Storyboard.SetTargetProperty(growUpStory, new PropertyPath(Grid.HeightProperty));
                growUpStory.Begin();

                Container.Visibility = Visibility.Visible;
            }
            else
            {
                Storyboard.SetTarget(growDownStory, Container);
                Storyboard.SetTargetProperty(growDownStory, new PropertyPath(Grid.HeightProperty));
                growDownStory.Begin();
                Container.Visibility = Visibility.Collapsed;
            }

I Try many ways but was unable to resolve. Where is my problem? have you any idea? thanks.

Upvotes: 0

Views: 214

Answers (1)

Tam Bui
Tam Bui

Reputation: 3038

Animations are asynchronous, which means you are collapsing the Visibility at the same time that you are starting the "growDownStory" animation.

Add some delay, based on how long you expect your "growDownStory" animation to run.

Example:

    growDownStory.Begin();
    await Task.Delay(1000); // allow time for the animation to perform its visual
    Container.Visibility = Visibility.Collapsed;

Upvotes: 2

Related Questions