对话框窗体上的WPF更新进度条

时间:2017-01-11 12:14:44

标签: c# wpf dialog progress-bar

我在表单上有一个ProgressBar,当父表单执行长操作时,我希望将其显示为对话框。

ProgressWindow很简单:

构造函数接受最大值,我有一个增量方法。

public ProgressWindow(int count)
{
    InitializeComponent();
    fileProgressBar.Maximum = count;
}

public void IncremntProgress()
{
    fileProgressBar.Value++;
}

在父母身上我创建了一个实例:

ProgressWindow progressWindow = new ProgressWindow(listOfFiles.Count);
progressWindow.Show();

然后我运行一个大型操作,我想更新进度条:

foreach (var file in listOfFiles)
{
    ....
    progressWindow.IncremntProgress();
}

progressWindow.Close();

这样可行,但我希望表单可以成为一个对话框,进度条不能正确刷新。

是否有更好的方法来更新对话框窗口上的进度条?

1 个答案:

答案 0 :(得分:0)

目前还不清楚“没有正确刷新”实际上意味着什么,但你应该在后台线程上运行“大操作”并在UI线程上更新任何UI元素,包括ProgressBar:

Task.Run(() =>
{
    //...
    foreach (var file in listOfFiles)
    {
        //...
        progressWindow.Dispatcher.Invoke(new Action(()=> progressWindow.IncremntProgress()));
    }
}).ContinueWith(task => 
{
    progressWindow.Close();
}, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

UI线程不能同时更新ProgressBar并同时运行您的操作/循环。

相关问题