I have got List<Object>
where the Object has a lot of childs List<Object>
around 4-6 levels.
Now I have to bind it to WPF TreeView... :(
Which the best way to convert it into ObservableCollection<Object>
is?
Assuming you mean ObservableCollection<T>
, if you wanted the List
directly to the ObservableCollection
as-is, just use the constructor:
var oc = new ObservableCollection<Object>(yourListOfObject);
Now, if you're wanting to unwind each of those, you would need to do some work to collapse them into a single ObservableCollection<T>
.
One part of the answer is to use Reactive Extensions (Rx). You can get it from NuGet and it's developed by Microsoft. With the help of it you can simply say: myListCollection.ToObservable();
If your child collections always are in a node with the same name you could use a while(item.Collection != null || item.Collection.Count == 0)
and put the ToObservable()
within the loop
Assuming you have a node class defined like so:
public class Node
{
public ICollection<Node> Children { get; set; }
}
You can use recursion to convert List<Node>
collections, at any level of depth:
public static ObservableCollection<Node> ToObservableRecursive(ICollection<Node> nodes)
{
foreach (Node node in nodes)
if (node.Children != null)
node.Children = ToObservableRecursive(node.Children);
return new ObservableCollection<Node>(nodes);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With