如何更新进度条以使其顺利增加?

TTG*_*oup 21 c# wpf progress-bar

我正在使用WPF(C#)的进度条来描述进程的进度.

我的算法如下:

DoSomethingCode1();
ProgressBar.SetPercent(10); // 10%
DoSomethingCode2();
ProgressBar.SetPercent(20); // 20%

...

DoSomethingCode10();
ProgressBar.SetPercent(100); // 100%
Run Code Online (Sandbox Code Playgroud)

没关系,但它会使进度条不连续.

有人可以告诉我一些让进度条轻柔更新的建议吗?

Owe*_*son 38

你可以使用一种行为!

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

你的XAML看起来像这样:

<ProgressBar local:ProgressBarSmoother.SmoothValue="{Binding Progress}">
Run Code Online (Sandbox Code Playgroud)

每当Progress你要绑定在XAML的变化特性,在ProgressBarSmoother行为的代码将运行,用适当的值加动画的进度条为您ToFrom!

  • 我添加了此解决方案,因为它允许您解耦报告进度和包含进度条的视图. (7认同)

Mat*_*kan 19

你可以把BeginAnimation动画的方法ProgressBarValue属性.在下面的例子中,我使用了一个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);          
    }
}
Run Code Online (Sandbox Code Playgroud)

所以在你的代码中你可以简单地调用:

myProgressBar.SetPercent(50);
Run Code Online (Sandbox Code Playgroud)

这样做可以简化过渡,使其看起来更好.引用另一个答案:"我们的想法是,进度条报告实际进度 - 而不是时间过去.它不是一个只表明正在发生的事情的动画." 但是,进度条的默认样式确实具有脉动效果,这可能意味着工作正在发生.

  • 对不起 - 经过一番研究 - 将presentationcore.dll添加到引用,然后"使用System.Windows.Media".请参阅[此Microsoft网站](http://msdn.microsoft.com/en-us/library/system.windows.media.animation.doubleanimation%28v=vs.110%29.aspx) (2认同)