WPF - 同步 UI 更新
如果我理解正确,则更改 WPF 中的任何控件(例如标签的文本)会将更新排入调度程序中。调度程序等待我的代码完成,当有时间时它会处理整个队列。
为此,调用
double current = 0;
ReportProgress (0d, "ProcessingStarted");
foreach (var item in collection)
{
item.Process(); //takes about 10s
current++;
ReportProgress (current / (double)collection.Count, "Processing item No. " + current.ToString () + " finished");
}
ReportProgress (1d, "Finished");
ReportProgress 调用带有此事件处理程序的事件时
private void handlerProgressMade (object sender, ProgressEventArgs e)
{
pbProgress.Value = pbProgress.Maximum * e.Percent;
lbProgressMessage.Content = e.Message;
}
,最终会显示完整的进度条和消息“已完成”,但不会显示步骤间。
我知道这可以通过在不同线程中调用函数并异步更新 UI 来完成(并且它会在某个时候发生),但目前添加线程似乎是不必要的复杂化。
如何强制Dispatcher立即更新并重绘?
If I understand correctly changing any control in WPF (eg. text of a Label) enqueues an update in Dispatcher. Dispatcher waits for my code to finish and when it has time it processes the whole queue.
For this, calling
double current = 0;
ReportProgress (0d, "ProcessingStarted");
foreach (var item in collection)
{
item.Process(); //takes about 10s
current++;
ReportProgress (current / (double)collection.Count, "Processing item No. " + current.ToString () + " finished");
}
ReportProgress (1d, "Finished");
where ReportProgress invokes an event with this event handler
private void handlerProgressMade (object sender, ProgressEventArgs e)
{
pbProgress.Value = pbProgress.Maximum * e.Percent;
lbProgressMessage.Content = e.Message;
}
ends up with full progressbar and message "Finished" displayed, but the intersteps are not shown.
I am aware that it could be done by calling the function in different thread and updating UI asynchronously (and it is going to happen at some point), but for now adding threads seems like unnecessary complication.
How to force the Dispatcher to update and redraw immediately?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不想使用后台线程,那么在设置进度条值之前和之后,
Application.DoEvents()
的旧技巧可能会有所帮助,因为它将等待清除所有堆积的消息队列在 GUI 消息总线中if you dont want to use background thread, then before and after you set the progress bar value, old hack of
Application.DoEvents()
might help as it will wait to clear all message queue that got piled up in the GUI Message Bus