使用CollectionViewSource时,如何在backgroundworker中加载数据?它抛出一个错误,因为我的CollectionViewSource在UI线程中。
这是我的所有代码(我在Xaml中设置的后台工作程序):
public partial class DepartmentsLookup : Window
{
private BackgroundWorker backgroundWorker;
private ObservableCollection<Department> AllDepartmentsData;
private ListCollectionView AllDepartmentsView;
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
IEnumerable<Department> data = null;
using (ArchiveEntities db = new ArchiveEntities())
{
data = db.Departments;
this.AllDepartmentsData = new ObservableCollection<Department>(data);
}
CollectionViewSource departmentsSource = (CollectionViewSource)this.FindResource("AllDepartmentsDataSource");
departmentsSource.Source = this.AllDepartmentsData;
this.AllDepartmentsView = (ListCollectionView)departmentsSource.View;
}
public DepartmentsLookup()
{
InitializeComponent();
backgroundWorker = ((BackgroundWorker)this.FindResource("backgroundWorker"));
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
backgroundWorker.RunWorkerAsync();
}
}谢谢。
发布于 2012-01-25 16:26:55
您必须使用WPF的Dispatcher对象(Dispatcher.Invoke)来执行UI元素上的代码(当使用BackgroundWorker完成时)。也许this article可以给你更多的信息。
或者working with the WPF Dispatcher。
https://stackoverflow.com/questions/8998936
复制相似问题