我有这种方法来更新我的TreeView
。如果我不使用BackgroundWorker
一切正常。但是如果这样做,那么我的TreeViewItem
不会更新,但它的DataContex会发生变化。这也很好:item.IsEnabled = false;
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);}
有什么想法吗?
答案 0 :(得分:1)
使用调用方法http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx(How to update the GUI from another thread in C#?),以下是http://www.codeproject.com/KB/tree/ThreadingTreeView.aspx的示例。
答案 1 :(得分:0)
我不确定问题是否更具体 WPF ;但如果是,那么这是我的建议:
如果您使用过DataBinding,这可能是一个DataContext解决问题,您的DataContext将被其他一些值覆盖/替换。请参考这两个关于DataContext如何工作的链接:
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