2

我正在尝试开发一个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%?

4

3 回答 3

10

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);
}
于 2013-07-11T14:00:51.223 回答
1

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

动画的目标值。

所以改变这个

DoubleAnimation doubleanimation = new DoubleAnimation(200.0, duration);

DoubleAnimation doubleanimation = new DoubleAnimation(progressBar1.Value, duration);
于 2013-07-11T13:48:18.713 回答
0

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

我写了这段代码:

 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);
        }
    }
}
于 2013-07-11T13:59:58.033 回答