使用特定值对进度条内容 WPF 进行动画处理

本文关键字:WPF 处理 动画 | 更新日期: 2023-09-27 18:21:55

我正在尝试开发一个ProgressBar,该根据我手动设置的值进行填充。例如,我有这个ProgressBar

<ProgressBar Height="33" HorizontalAlignment="Left" Name="progressBar1" VerticalAlignment="Top" Width="285" />

我有一个按钮,每次按下它时,ProgressBar值都会增加 10 个单位,如下所示:

private void button1_Click(object sender, RoutedEventArgs e)
{
    progressBar1.Value += 10;
}

我想在每次单击它时对该值更改进行动画处理。我试过这个:

Duration duration = new Duration(TimeSpan.FromSeconds(1));
DoubleAnimation doubleanimation = new DoubleAnimation(200.0, duration);
progressBar1.BeginAnimation(ProgressBar.ValueProperty, doubleanimation);

但它从 0 到 100 的值 ProgressBar .如何告诉动画在特定值上停止,而不是转到 100%?

使用特定值对进度条内容 WPF 进行动画处理

如果您执行以下操作,则实际上是将Value动画设置为最终值 200:

DoubleAnimation doubleanimation = new DoubleAnimation(200.0, duration);

而是将第一个参数更改为要动画化的值。事件处理程序应如下所示:

private void button1_Click(object sender, RoutedEventArgs e)
{
    Duration duration = new Duration(TimeSpan.FromSeconds(1));
    DoubleAnimation doubleanimation = new DoubleAnimation(progressBar1.Value + 10, duration);
    progressBar1.BeginAnimation(ProgressBar.ValueProperty, doubleanimation);
}

DoubleAnimation Constructor (Double, Duration)第一个参数是

动画的目标值。

所以改变这个

DoubleAnimation doubleanimation = new DoubleAnimation(200.0, duration);

DoubleAnimation doubleanimation = new DoubleAnimation(progressBar1.Value, duration);

对于那些感兴趣的人,我在此链接中找到了一个解决方案。它解释了如何使用BackgroundWorker填充ProgressBar值。

我写了这段代码:

 public MainWindow()
 {
    InitializeComponent();
    backgroundworker.WorkerReportsProgress = true;
    backgroundworker.WorkerSupportsCancellation = true;
    backgroundworker.DoWork += backgroundworker_DoWork;
    backgroundworker.ProgressChanged += backgroundworker_ProgressChanged;
}
private void buttonStop_Click(object sender, RoutedEventArgs e)
{
    backgroundworker.CancelAsync();
    e.Handled = true;
}
private void buttonStart_Click(object sender, RoutedEventArgs e)
{
    if (backgroundworker.IsBusy == false)
    {
       backgroundworker.RunWorkerAsync();
    }
    e.Handled = true;
}
void backgroundworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}
void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    if (worker != null)
    {
        for (int i = 0; i <= 10; i++)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
                break;
            }
            System.Threading.Thread.Sleep(50);
            worker.ReportProgress(i);
        }
    }
}