Animate height of groupbox from 0 to auto

2020-08-13 04:49发布

问题:

I have groupboxes acting like expanders in my application. When I need to colapse a groupbox I set its height equal to 0. when I need to expand it I set it's height equal to auto (double.Nan) is it posible to do this with a storyboard. How could I know the auto height in advance. Expression blend does not enable me to animate to an auto.

回答1:

You can use ScaleTransform for this

<GroupBox Header="GroupBox">
    <GroupBox.RenderTransform>
        <ScaleTransform ScaleY="1"/>
    </GroupBox.RenderTransform>
</GroupBox>

When collapse a groupbox set ScaleTransform.ScaleX to 0. And when expand set to 1.



回答2:

As I hate scale transformation because I find it ugly, I looked for another solution.

Well, I know it is an old post and many workarounds exist, but mine is quite simple, and I didn't read it elsewhere even if someone found it for sure.
Instead of animating the height from X to Auto (which is impossible), you could let the height to Auto and animate the MaxHeight property:

<MyControl x:Name="ctrlAutoHeight" Height="Auto">
    <MyControl.Triggers>
        <EventTrigger RoutedEvent="myRoutedEvent">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation 
                        Storyboard.TargetName="ctrlAutoHeight" 
                        Storyboard.TargetProperty="MaxHeight"
                        From="0.0" 
                        To="{Binding ElementName=ParentControl, Path=ActualHeight}"
                        Duration="0:0:1" 
                        AutoReverse="False"
                        />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </MyControl.Triggers>
</MyControl>