在后台线程中WPF更新绑定 [英] WPF update binding in a background thread

查看:565
本文介绍了在后台线程中WPF更新绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控件,它的数据绑定到一个标准的 ObservableCollection ,我有一个后台任务调用服务来获取更多的数据。

I have a control that has its data bound to a standard ObservableCollection, and I have a background task that calls a service to get more data.

然后,我想更新我的控件背后的数据,同时显示一个请等待对话框,但是当我将新的项目添加到集合中时,UI线程锁定它可以重新绑定和更新我的控件。

I want to, then, update my backing data behind my control, while displaying a "please wait" dialog, but when I add the new items to the collection, the UI thread locks up while it re-binds and updates my controls.

我可以解决这个问题,以便我的动画和内容继续运行在我的请等待对话框上?

Can I get around this so that my animations and stuff keep running on my "please wait" dialog?

或至少给用户没有锁定的外观?

Or at least give the "appearance" to the user that its not locked up?

推荐答案

p>如果我理解正确,您已经使用了BackgroundWorker来检索数据,只需将该数据分配给ObservableCollection即可锁定用户界面。

If i understand correctly, you already use a BackgroundWorker to retrieve the data, and that simply assigning this data to the ObservableCollection is locking up the UI.

避免锁定UI是通过排队多个分派器方法将数据分配给较小块中的ObservableCollection。在每个方法调用之间,可以处理UI事件。

One way to avoid locking up the UI is to assign the data to the ObservableCollection in smaller chunks by queuing multiple dispatcher methods. Between each method call, UI events can be handled.

以下将一次添加一个项目,这有点极端,但它说明了这个概念。 p>

the following would add one item on at a time, that's a bit extreme, but it illustrates the concept.

void UpdateItems()
{
    //retrievedItems is the data you received from the service
    foreach(object item in retrievedItems)
        Dispatcher.BeginInvoke(DispatcherPriority.Background, new ParameterizedThreadStart(AddItem), item);    
}

void AddItem(object item)
{
    observableCollection.Add(item);
}

这篇关于在后台线程中WPF更新绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆