简体   繁体   中英

How to Trigger animation in WPF using C#

I want to play animation using c# when i press Crtl

private void rtb_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
    {
        //lstBox1.Opacity = 1;
        //here i want to play fadeIn animation
    }
}

Assuming listBox1 is declared in XAML and you want to apply Fade-In animation on it. You can toggle opacity from 0 to 1 like this:

DoubleAnimation animation = new DoubleAnimation(0.0, 1.0,
                                             new Duration(new TimeSpan(0,0,1)));
listBox1.BeginAnimation(ListBox.OpacityProperty, animation);

You can achieve that with Storyboard as well (but definitely no use when you can achieve that simply using double animation):

DoubleAnimation animation = new DoubleAnimation(0.0, 1.0,
                               new Duration(new TimeSpan(0, 0, 2)));
Storyboard storyBoard = new Storyboard();
storyBoard.Children.Add(animation);
Storyboard.SetTarget(animation, listBox);
Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
storyBoard.Begin();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM