3

我有这个方法来更新我的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);}

有任何想法吗?

4

2 回答 2

1

使用 Invoke 方法http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx如何从 C# 中的另一个线程更新 GUI?),这里是一个例子http://www.codeproject.com /KB/tree/ThreadingTreeView.aspx

于 2011-11-07T08:57:34.580 回答
0

我不确定问题是否更特定于WPF;但如果是,那么这是我的建议:

如果您使用过 DataBinding,这可能是 DataContext 解决问题,您的 DataContext 被其他值覆盖/替换。请参阅以下 2 个链接,了解 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

于 2011-11-07T12:24:19.573 回答