How to update a progress bar so it increases smoothly?

前端 未结 4 1626
野性不改
野性不改 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:36

    You could call the BeginAnimation method to animate the ProgressBar's Value property. In my example below, I used a DoubleAnimation.

    I created an extension method that takes in the desired percentage:

    public static class ProgressBarExtensions
    {
        private static TimeSpan duration = TimeSpan.FromSeconds(2);
    
        public static void SetPercent(this ProgressBar progressBar, double percentage)
        {
            DoubleAnimation animation = new DoubleAnimation(percentage, duration);
            progressBar.BeginAnimation(ProgressBar.ValueProperty, animation);          
        }
    }
    

    So in your code you could simply call:

    myProgressBar.SetPercent(50);
    

    Doing this simply smooths out the transition so it looks nicer. To quote another answer: "The idea is that a progress bar reports actual progress - not time elapsed. It's not intended to be an animation that just indicates something is happening." However, the default style of the progress bar does have a pulsating effect which can imply work is happening.

提交回复
热议问题