Slide in & Slide out animation

2019-04-09 14:30发布

问题:

I am trying to make a slide in & out animation with c# & WPF.

So far I have managed to code the next lines:

XAML:

<Grid Name="grid" Grid.Column="0" Grid.Row="1">
       <Border Name="border" Background="Red"></Border>
</Grid>

c#:

private void Button_Click(object sender, RoutedEventArgs e) {
            border.Height = grid.ActualHeight;
            if (!isOpen) {
                isOpen = true;
                DoubleAnimation db = new DoubleAnimation();
                db.From = 0;
                db.To = grid.ActualHeight;
                db.Duration = TimeSpan.FromSeconds(0.5);
                border.BeginAnimation(Grid.HeightProperty, db);
            } else {
                isOpen = false;
                DoubleAnimation db = new DoubleAnimation();
                db.From = grid.ActualHeight;
                db.To = 0;
                db.Duration = TimeSpan.FromSeconds(0.5);
                border.BeginAnimation(Grid.HeightProperty, db);
            }
        }

The good thing is that the animation is executed. The bad thing is that this animation has the wrong effect, i mean the animation goes from top to middle and bottom to middle (like if it was shrinking)...

How can i make (or modify in my actual code) the slide effect(top to bottom & bottom to top)?

It has to be in c# code.

回答1:

You are trying to translate your UI control so use a TranslateTransform (Canvas.Top is possible if you are on a canvas, but inefficient).

Modify your XAML to include a render transform set to a TranslateTransform object:

<Grid Name="grid" Grid.Column="0" Grid.Row="1" ClipToBounds="true">
    <Border Name="border" Background="Red">
       <Border.RenderTransform>
           <TranslateTransform x:Name="borderTransform"/>
       </Border.RenderTransform>
    </Border>
</Grid>

And animate the Y property of the transform:

DoubleAnimation db = new DoubleAnimation();
db.From = 0;
db.To = grid.ActualHeight;
db.Duration = TimeSpan.FromSeconds(0.5);
borderTransform.BeginAnimation(TranslateTransform.YProperty, db);

Just so you know, doing this is a whole lot cleaner using a Storyboard object (plus you can set it up in XAML!)



标签: c# wpf animation