WPF Animation of border width

2019-09-16 20:45发布

问题:

I've got a dockpanel on my ui as follows;

<DockPanel>
    <Border DockPanel.Dock="Top">Header</Border>
    <Border DockPanel.Dock="Bottom">My footer</Border>
    <Border DockPanel.Dock="Left">Menu</Border>

    <Border>Content</Border>
 </DockPanel>

What I want to do is to have a storyboard animation to show / hide the Menu on the left-hand side. I've got my border to increase the width when it has loaded but I want a way to close / reopen it. I need a button somewhere but I want this to trigger the animation in the border control rather than itself. Ideally I was thinking of something like the Toolbox / Server Explorer in visual studio.

Does anyone have any pointers / examples for getting started?

Thanks

回答1:

I'm not sure I understand what you mean, but if you want to animate it in/out then you probably want to update its width? If you have a property on your ViewModel/PresentationModel that you can bind to then you can do something like:

<DataTrigger Binding="{Binding IShouldBeVisible}" Value="True">
    <DataTrigger.EnterActions>
        <BeginStoryboard>
            <Storyboard AccelerationRatio="0.4" DecelerationRatio="0.4">
                <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.Width)">
                    <SplineDoubleKeyFrame KeyTime="00:00:0.13" Value="100"/>
                </DoubleAnimationUsingKeyFrames>
            </Storyboard>
        </BeginStoryboard>
    </DataTrigger.EnterActions>
    <DataTrigger.ExitActions>
        <BeginStoryboard>
            <Storyboard AccelerationRatio="0.4" DecelerationRatio="0.4">
                <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.Width)">
                    <SplineDoubleKeyFrame KeyTime="00:00:0.1" Value="0"/>
                </DoubleAnimationUsingKeyFrames>
            </Storyboard>
        </BeginStoryboard>
    </DataTrigger.ExitActions>
</DataTrigger>

If you are doing complicated animations that change multiple properties, different timings etc then it's much easier to put together in Blend, even if you do it in a test project then cut+paste the resulting StoryBoard :-)