如何更新进度条以使其顺利增加?
我正在使用WPF(C#)的进度条来描述进程的进度。
我的算法如下:
DoSomethingCode1(); ProgressBar.SetPercent(10); // 10% DoSomethingCode2(); ProgressBar.SetPercent(20); // 20% ... DoSomethingCode10(); ProgressBar.SetPercent(100); // 100%
没关系,但它会使进度条不连续。
有人可以告诉我一些让进度条轻柔更新的建议吗?
您可以调用BeginAnimation
方法来为ProgressBar
的Value
属性设置动画。 在下面的示例中,我使用了DoubleAnimation
。
我创建了一个获取所需百分比的扩展方法:
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); } }
所以在你的代码中你可以简单地调用:
myProgressBar.SetPercent(50);
这样做可以简化过渡,使其看起来更好。 引用另一个答案 :“我们的想法是,进度条报告实际进度 – 而不是时间过去。它并不是一个只表明正在发生的事情的动画。” 但是,进度条的默认样式确实具有脉动效果,这可能意味着工作正在发生。
你可以使用一种行为!
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); } }
你的XAML看起来像这样:
每当您在xaml中绑定的Progress
属性发生更改时,ProgressBarSmoother行为中的代码将会运行,将动画添加到进度条中,并为To
和From
适当的值!
检查是否可以修改进度条的样式,并将Easing函数设置为修改进度条“填充”的故事板,并通过这样做,它将平滑过渡。
试试这个。
private void updateProgressBar(int percent) { if (ProgressBar.InvokeRequired) { updateProgressBarCallback cb = new updateProgressBarCallback(updateProgressBar); this.Invoke(cb, new object[] { percent }); } else { ProgressBar.Value = percent; ProgressBar.Update(); ProgressBar.Refresh(); ProgressBar.Invalidate(); }