0
votes

I'm following this article to try and programmatically bind data to a treeview (I'm on 1903).

In a brand new UWP app, I have the following code behind:

public MainPage()
{
    this.InitializeComponent();

    var items = new List<Item>();
    var rootItem = new Item();
    rootItem.Name = "Root Item";
    rootItem.Children.Add(new Item() { Name = "test child 1" });
    items.Add(rootItem);

    var treeView = new TreeView();
    treeView.ItemsSource = items;
    stackPanel.Children.Add(treeView);
}

Item looks like this:

public class Item
{
    public string Name { get; set; }
    public ObservableCollection<Item> Children { get; set; } = new ObservableCollection<Item>();

    public override string ToString()
    {
        return Name;
    }
}

This appears to be the exact structure outlined in the above article. However, when I run the application, I get this:

UWP App TreeView

My guess is that I need to do, or set something that tells this treeview, or the collection that it has children - but I can't see what that might be.

2

2 Answers

0
votes

You should create an ItemTemplate as explained in the docs.

You could use the XamlReader class to do this programmatically. Something like this:

const string Xaml = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><TreeViewItem ItemsSource=\"{Binding Children}\" Content=\"{Binding Name}\"/></DataTemplate>";
treeView.ItemTemplate = XamlReader.Load(Xaml) as DataTemplate;
0
votes

If you use C# to build a TreeView, I recommend adding a TreeViewNode using traversal.

Due to the lack of instructions, TreeView does not automatically handle the Children of the Item. In the documentation you provide, the TreeView has a DataTemplate directive, so the children can render.

You can change code like this:

public MainPage()
{
    this.InitializeComponent();
    var items = new List<Item>();
    var rootItem = new Item();
    rootItem.Name = "Root Item";
    rootItem.Children.Add(new Item() { Name = "test child 1" });
    items.Add(rootItem);
    var treeView = new TreeView();

    foreach (var root in items)
    {
        var rootNode = new TreeViewNode() { Content = root.Name };
        if (root.Children.Count > 0)
        {
            foreach (var child in root.Children)
            {
                rootNode.Children.Add(new TreeViewNode() { Content = child.Name });
            }
        }
        treeView.RootNodes.Add(rootNode);
    }
    stackPanel.Children.Add(treeView);
}

Best regards.