How to update a progress bar so it increases smoothly?

前端 未结 4 1627
野性不改
野性不改 2020-12-14 08:05

I\'m using progress bar of WPF (C#) to describe the process\'s progress.

My algorithm is below:

DoSomethingCode1();
ProgressBar.SetPercent(10); // 10         


        
4条回答
  •  难免孤独
    2020-12-14 08:53

    You can use a behavior!

    public class ProgressBarSmoother
    {
        public static double GetSmoothValue(DependencyObject obj)
        {
            return (double)obj.GetValue(SmoothValueProperty);
        }
    
        public static void SetSmoothValue(DependencyObject obj, double value)
        {
            obj.SetValue(SmoothValueProperty, value);
        }
    
        public static readonly DependencyProperty SmoothValueProperty =
            DependencyProperty.RegisterAttached("SmoothValue", typeof(double), typeof(ProgressBarSmoother), new PropertyMetadata(0.0, changing));
    
        private static void changing(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var anim = new DoubleAnimation((double)e.OldValue, (double)e.NewValue, new TimeSpan(0,0,0,0,250));
            (d as ProgressBar).BeginAnimation(ProgressBar.ValueProperty, anim, HandoffBehavior.Compose);
        }
    }
    

    Your XAML would look like this:

    
    

    Whenever the Progress property you are binding to in the xaml changes, the code in the ProgressBarSmoother behavior will run, adding the animation to the progress bar for you with the appropriate values for To and From!

提交回复
热议问题