3

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?

S2S2
  • 8,322
  • 5
  • 37
  • 65
algreat
  • 8,592
  • 5
  • 41
  • 54

2 Answers2

1

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.

Community
  • 1
  • 1
Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
  • I think backgroundworker's runworkercompleted event already runs on UI thread and UI updates should not be an issue in this event.. – S2S2 Nov 07 '11 at 11:04
  • @Vijay, of course it should run in UI thread but there is a bug (probably), more info [BackgroundWorker OnWorkCompleted throws cross-thread exception](http://stackoverflow.com/questions/818767/backgroundworker-onworkcompleted-throws-cross-thread-exception/897848#897848) – Michał Powaga Nov 07 '11 at 12:11
0

I am not sure if the problem is more WPF specific; but if it is then here are my suggestions:

If you have used DataBinding, this might be a DataContext resolving problem, your DataContext is getting overwritten/replaced by some other value. Please refer these 2 links on how DataContext works:

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

S2S2
  • 8,322
  • 5
  • 37
  • 65