如何在C#中使用ProgressBar?

时间:2015-08-27 14:50:51

标签: c# windows-phone-8.1 windows-phone progress-bar

我想使用ProgressBar并在2秒内将其从100%运行到0%。我写了以下函数,但它似乎没有正常运行。请帮忙!谢谢!

private async void progessbar()
{
    for (iValue = 100; iValue >= 0; iValue--)
    {
        pbTime.Value = iValue;
        await Task.Delay(20);
    }
}

3 个答案:

答案 0 :(得分:4)

如果要平滑地为进度条设置动画,则应使用故事板:

private void AnimateProgressBar()
{
    var storyboard = new Storyboard();

    var animation = new DoubleAnimation { Duration = TimeSpan.FromSeconds(2), From = 100, To = 0, EnableDependentAnimation = true };

    Storyboard.SetTarget(animation, this.ProgressBar);
    Storyboard.SetTargetProperty(animation, "Value");

    storyboard.Children.Add(animation);

    storyboard.Begin();
}

答案 1 :(得分:0)

您正在同一Windows事件中多次更改工具栏。 Windows稍后在空闲时更新GUI。因此,您可能会看到您的工具栏在等待2秒后从0跳到100%。

只需向控件添加计时器,在准备启动时进行设置并进行增量更新。

// In your designer:
this.timer.Enabled = false;
this.timer.Interval = 200;
this.timer.Tick += new System.EventHandler(this.timer_Tick);

// when starting the progress:  
pbTime.Value = 0
this.timer.Enabled = true; 

private void timer_Tick(object sender, EventArgs e)
{
    if (pbTime.Value < 100)
        pbTime.Value += 10;

}

答案 2 :(得分:0)

我希望这会有所帮助

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

private void Form1_Load(object sender, System.EventArgs e)
{
    // Start the BackgroundWorker.
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    /*Your main code*/
    for (int i = 1; i <= 100; i++)
    {
    // Wait 20 milliseconds.
    Thread.Sleep(20);
    // Report progress.
    backgroundWorker1.ReportProgress(i);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // Change the value of the ProgressBar to the BackgroundWorker progress.
    progressBar1.Value = e.ProgressPercentage;
    // Set the text.
    this.Text = e.ProgressPercentage.ToString();
}
}

}