There are a lot of questions on here about updating controls(mainly the ObservableCollection
) using a background worker thread. I am trying to implement this solution. However, my situation has just a little bit more depth to it because it calls to a function in the add method that returns the object to be added.
This is what my solution looks like right now (note that my ObservableCollection
is bound to a TreeView
control):
//Pass from Background Thread
MainTreeViewModel.AddLocation(locationName, locationValue);
//UI Thread (MainTreeViewModel)
public void AddLocation(MultiItemString displayName, int locationValue)
{
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'P'); //Location Parent
App.Current.Dispatcher.BeginInvoke((Action)delegate()
{
node.Children.Add(CreateLocationNode(displayName, locationValue));
});
}
CreateLocationNode:
//Also location in MainTreeViewModel
private HierarchicalVM CreateLocationNode(MultiItemString displayName, int locationValue)
{
MultiItemString locationNumber = new MultiItemString(new[] {locationValue.ToString() + " "}, false);
var newLocationNode = new HierarchicalVM()
{
DisplayName = displayName, //Examples of props that turn out as NULL
LocationNumber = locationNumber,
TreeView_LocValue = locationValue,
Children = new ObservableCollection<HierarchicalVM>(), //This is what is being added to
Commands =
};
return newLocationNode;
}
When doing this I find that an object gets added, but all of the properties attached to it receive null values. Oppositely, when I am doing everything in the UI thread and just using node.Children.Add(CreateLocationNode(displayName, locationValue));
, everything attaches how it should. Why am I getting a different result here, and how can I fix it?
Please let me know if you need more code.