[英]WPF Update progress bar on dialog form
I have a ProgressBar on a form which I want to show as a dialog when the parent form is performing a long operation. 我在窗体上有一个ProgressBar,当父窗体执行长时间操作时,我想将其显示为对话框。
The ProgressWindow is simple: ProgressWindow很简单:
The constructor takes in the max value and I have an increment method. 构造函数接受最大值,我有一个增量方法。
public ProgressWindow(int count)
{
InitializeComponent();
fileProgressBar.Maximum = count;
}
public void IncremntProgress()
{
fileProgressBar.Value++;
}
On the parent I create an instance: 在父级上,我创建一个实例:
ProgressWindow progressWindow = new ProgressWindow(listOfFiles.Count);
progressWindow.Show();
I then run a large operation and I want to update the progressbar: 然后,我运行一个大型操作,并且想要更新进度条:
foreach (var file in listOfFiles)
{
....
progressWindow.IncremntProgress();
}
progressWindow.Close();
This works but I'd like the form to be a dialog and the progress bar doesn't refresh correctly. 这可行,但是我希望表单是一个对话框,并且进度条无法正确刷新。
Is there a better way of updating a progress bar on a dialog window? 有没有更好的方法来更新对话框窗口上的进度条?
It's unclear what "doesn't refresh correctly" actually means here but you should run the "large operation" on a background thread and update any UI elements including the ProgressBar back on the UI thread: 尚不清楚“未正确刷新”在这里实际上是什么意思,但是您应该在后台线程上运行“大操作”,并在UI线程上重新更新包括ProgressBar在内的所有UI元素:
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());
The UI thread cannot both update the ProgressBar and run your operation/loop simultaneously. UI线程无法同时更新ProgressBar和同时运行操作/循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.