.netwpfxamlwpf-controlswpf-4.0

WPF animating a StackPanel's width from 0 to Auto?


I am trying to animate a StackPanel when its visibility changed to grow from a width of 0 to its automatic width, here is what I have at the moment:

<Trigger Property="Visibility" Value="Visible">
    <Setter Property="Width" Value="0"></Setter>
    <Trigger.EnterActions>
        <BeginStoryboard>
            <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Width" Duration="0:0:1">
                    <DiscreteObjectKeyFrame KeyTime="0">
                        <DiscreteObjectKeyFrame.Value>
                            <System:Double>NaN</System:Double>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </BeginStoryboard>
    </Trigger.EnterActions>
</Trigger>

Can someone explain how I might achieve this animation? Is it maybe not possible in the way I am trying to do it?

Thanks, alex.


Solution

  • Here is a quick mockup project I threw together.

    In the Window's Loaded event, I simply set the stackpanel's visibility to Visible and it expands to fit its container width from left to right... Hopefully that's suits your needs.

    Some things to note:

    And here is the code:

    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="600" Loaded="Window_Loaded">
        <Border HorizontalAlignment="Center" Width="300" Background="Gainsboro">
            <Border.Resources>
                <Style TargetType="StackPanel" x:Key="expand">
                    <Setter Property="RenderTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX="1"/>
                        </Setter.Value>
                    </Setter>
                    <Style.Triggers>
                        <Trigger Property="Visibility" Value="Visible">
                            <Trigger.EnterActions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetProperty="RenderTransform.ScaleX"
                                                         From="0"
                                                         Duration="0:00:01"/>
                                    </Storyboard>
                                </BeginStoryboard>
                            </Trigger.EnterActions>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Border.Resources>
    
            <StackPanel x:Name="stackpanel" Background="Gray" Visibility="Collapsed" Style="{StaticResource expand}"/>
    
        </Border>
    </Window>