Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeViewItem can't update in BackgroundWorker

I have this method to update my TreeView. If i don't use BackgroundWorker all works fine. But if do then my TreeViewItem doesn't update, but it's DataContex changes. Also this works fine: 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);}

Any ideas?

like image 639
algreat Avatar asked Feb 17 '26 09:02

algreat


1 Answers

Use Invoke method http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx ( How to update the GUI from another thread in C#? ), here is an example how http://www.codeproject.com/KB/tree/ThreadingTreeView.aspx.

like image 97
Michał Powaga Avatar answered Feb 19 '26 22:02

Michał Powaga