2011-10-26 64 views
3

我有這種方法來更新我的TreeView。如果我不使用BackgroundWorker所有工作正常。但如果這樣做,那麼我的TreeViewItem不會更新,但它是DataContex更改。此工作正常:item.IsEnabled = false;TreeViewItem無法更新BackgroundWorker

private void twSports_Expanded(object sender, RoutedEventArgs e)  
{  
TreeViewItem item = e.OriginalSource as TreeViewItem; 
TreeLeaf leaf = item.DataContext as TreeLeaf; var bgWorker = new BackgroundWorkerOnGrid(gridPartitions); 
bgWorker.DoWork += delegate(object s, DoWorkEventArgs args) 
{    
    if (leaf.Item != null) 
    { 
     if (leaf.Item.GetType() == typeof(SportType)) 
     { 
      SportType sport = leaf.Item as SportType; 
      args.Result = LoadSportPartitions(sport); 
     } 
     if (leaf.Item.GetType() == typeof(SportPartition)) 
     { 
      SportPartition partition = leaf.Item as SportPartition; 
      args.Result = LoadSportPartitions(partition); 
     } 
    } 
}; 

bgWorker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) 
{ 
    List<SportPartition> partitions = args.Result as List<SportPartition>; 

    if (partitions != null) 
    { 
     leaf.LoadChilds(partitions.ToArray()); //it doesn't work 
     item.IsEnabled = false; //it works 
    } 

    (s as BackgroundWorkerOnGrid).Dispose(); 
}; 

bgWorker.RunWorkerAsync(leaf.Item);} 

任何想法?

回答

1
+0

我想的BackgroundWorker的RunWorkerCompleted事件已經運行在UI線程和UI更新不應該在此事件中的一個問題。 。 – VS1

+0

@Vijay,當然它應該在UI線程中運行,但有一個錯誤(可能),更多信息[BackgroundWorker OnWorkCompleted拋出跨線程異常](http://stackoverflow.com/questions/818767/backgroundworker-onworkcompleted-拋出,交叉線程異常/ 897848#897848) –

0

我不確定問題是否更多WPF具體;但如果是這樣,那麼這裏是我的建議:

如果您使用過DataBinding,這可能是一個DataContext解決問題,您的DataContext被覆蓋/替換爲其他值。請參閱有關的DataContext如何工作的這2個環節:

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx

http://msdn.microsoft.com/en-us/library/ms752347.aspx

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontextchanged.aspx