我有這種方法來更新我的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);}
任何想法?
我想的BackgroundWorker的RunWorkerCompleted事件已經運行在UI線程和UI更新不應該在此事件中的一個問題。 。 – VS1
@Vijay,當然它應該在UI線程中運行,但有一個錯誤(可能),更多信息[BackgroundWorker OnWorkCompleted拋出跨線程異常](http://stackoverflow.com/questions/818767/backgroundworker-onworkcompleted-拋出,交叉線程異常/ 897848#897848) –