Search code examples
c#wpfanimationstackpanel

Problems hiding WPF StackPanel (not expander)


I have a real trouble with WPF StackPanel - I need to make it animated not only for scrolling its content horizontaly (this is ok more or less), but also I must make it expand/collapse (animated) by pressing some button on the containing window.

I have tried a lot of animated expander controls (for example http://www.codeproject.com/KB/WPF/AnimatingExpander.aspx) but they have overloaded with functionality (and some artifacts with contained controls) and not suitable for my task.

So the question is how to make SIMPLE horizontal oriented StackPanel to expand/collapse with animation by button click?


Solution

  • The simplest approach is to start an animation on a ToggleButton.Checked or .Unchecked event:

    <StackPanel x:Name="MyStackPanel">...</StackPanel>
    
    ...
    
    <ToggleButton Content="Click Me">
        <ToggleButton.Triggers>
            <EventTrigger RoutedEvent="ToggleButton.Checked">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="MyStackPanel" 
                                         Storyboard.TargetProperty="Width"
                                         To="0"
                                         Duration="0:0:0.5" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
            <EventTrigger RoutedEvent="ToggleButton.Unchecked">
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="MyStackPanel" 
                                         Storyboard.TargetProperty="Width"
                                         To="200"
                                         Duration="0:0:0.5" />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </ToggleButton.Triggers>
    </ToggleButton>