TreeViewItem无法在BackgroundWorker中更新

3

我有一个更新TreeView的方法。如果我不使用BackgroundWorker,一切都很好。但是,如果我用了,我的TreeViewItem就不会更新,但它的数据内容确实发生了改变。另外,这个也可以正常工作: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);}

有什么想法吗?
2个回答

1

我认为BackgroundWorker的RunWorkerCompleted事件已经在UI线程上运行,因此在此事件中进行UI更新不应该是一个问题。 - S2S2
@Vijay,当然它应该在UI线程中运行,但是有一个错误(可能),更多信息请参见BackgroundWorker OnWorkCompleted throws cross-thread exception - Michał Powaga

0

我不确定问题是否更多涉及于WPF;但如果是的话,这里是我的建议:

如果您使用了数据绑定,那么可能是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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接