1

如何在使用CollectionViewSource時在backgroundworker中加載數據?它會拋出一個錯誤,因爲我的CollectionViewSource在UI線程中。BackgroundWorker和CollectionViewSource

這是我所有的代碼(我的背景工人在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(); 
    } 
} 

感謝名單。

+1

我沒有看到背景工作。但是當您設置collectionview時,您必須使用調度程序 – blindmeis

+0

什麼異常以及它在哪裏拋出? –

+0

我更新我的問題。 –

回答

2

您必須使用WPF的Dispatcher對象(Dispatcher.Invoke)才能在UI元素上執行代碼(當從backgroundWorker完成時)。也許this article可以給你一些更多的信息。

working with the WPF Dispatcher

+1

你的第二個鏈接幫助我。非常感謝你。 –