WPF - 同步UI更新

时间:2011-07-27 10:44:39

标签: wpf user-interface dispatcher synchronous

如果我理解正确更改WPF中的任何控件(例如标签的文本),则在Dispatcher中将更新排入队列。 Dispatcher等待我的代码完成,并在有时间处理整个队列。

为此,请致电

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立即更新和重绘?

1 个答案:

答案 0 :(得分:0)

如果您不想使用后台线程,那么在设置进度条值之前和之后,Application.DoEvents()的旧hack可能会有所帮助,因为它将等待清除在GUI消息中堆积的所有消息队列总线