Using ItemTemplate for a TreeView when adding items in code

27,064

Your ItemTemplate is trying to render a "Name" and "Age" property in TextBlocks, but TreeViewItem doesn't have an "Age" property and you aren't setting its "Name".

Because you're using an ItemTemplate, there's no need to add TreeViewItems to the tree. Instead, add your Person instances directly:

_treeView.Items.Add(new Person { Name = "Sally", Age = 28});

The problem, of course, is that your underlying object ("Person") doesn't have any concept of hierarchy, so there's no simple way to add "Joe" to "Sally". There are a couple of more complex options:

You could try handling the TreeView.ItemContainerGenerator.StatusChanged event and wait for the "Sally" item to be generated, then get a handle to it and add Joe directly:

public Window1()
{
    InitializeComponent(); 
    var bob = new Person { Name = "Bob", Age = 34 }; 
    var sally = new Person { Name = "Sally", Age = 28 }; 

    _treeView.Items.Add(bob); 
    _treeView.Items.Add(sally);

    _treeView.ItemContainerGenerator.StatusChanged += (sender, e) =>
    {
        if (_treeView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) 
            return;

        var sallyItem = _treeView.ItemContainerGenerator.ContainerFromItem(sally) as TreeViewItem;
        sallyItem.Items.Add(new Person { Name = "Joe", Age = 15 });
    };
}

Or, a better solution, you could introduce the hierarchy concept into your "Person" object and use a HierarchicalDataTemplate to define the TreeView hierarchy:

XAML:

<Window x:Class="TreeTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WindowTree" Height="300" Width="300">
    <Grid>
        <TreeView Name="_treeView">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Subordinates}">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=Name}" />
                        <TextBlock Text="{Binding Path=Age}" />
                    </StackPanel>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>
</Window>

CODE:

using System.Collections.Generic;
using System.Windows;

namespace TreeTest
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent(); 
            var bob = new Person { Name = "Bob", Age = 34 }; 
            var sally = new Person { Name = "Sally", Age = 28 }; 

            _treeView.Items.Add(bob); 
            _treeView.Items.Add(sally);
            sally.Subordinates.Add(new Person { Name = "Joe", Age = 15 });
        }

    }
    public class Person 
    {
        public Person()
        {
            Subordinates = new List<Person>();
        }

        public string Name { get; set; } 
        public int Age { get; set; }
        public List<Person> Subordinates { get; private set;  }
    }
}

This is a more "data-oriented" way to display your hierarchy and a better approach IMHO.

Share:
27,064
kumar TN
Author by

kumar TN

I am an application developer with full Systems Development Life Cycle experience. After 10 years working with real time financial systems I know how to develop multithreaded applications which supports traders and bankers every need. My specialty is Windows development using .NET technology, preferably C#. SQL Server programming is another area where I have extensive experience with. Currently I am using Windows Presentation Foundation (WPF) in order to take financial applications to the next level.

Updated on July 18, 2022

Comments

  • kumar TN
    kumar TN almost 2 years

    I'm adding TreeViewItems manually in code behind and would like to use a DataTemplate to display them but can't figure out how to. I'm hoping to do something like this but the items are displayed as empty headers. What am I doing wrong?

    XAML

    <Window x:Class="TreeTest.WindowTree"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WindowTree" Height="300" Width="300">
        <Grid>
            <TreeView Name="_treeView">
                <TreeView.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Path=Name}" />
                            <TextBlock Text="{Binding Path=Age}" />
                        </StackPanel>
                    </DataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>
        </Grid>
    </Window>
    

    Behind code

    using System.Windows;
    using System.Windows.Controls;
    
    namespace TreeTest
    {
        public partial class WindowTree : Window
        {
            public WindowTree()
            {
                InitializeComponent();
    
                TreeViewItem itemBob = new TreeViewItem();
                itemBob.DataContext = new Person() { Name = "Bob", Age = 34 };
    
                TreeViewItem itemSally = new TreeViewItem();
                itemSally.DataContext = new Person() { Name = "Sally", Age = 28 }; ;
    
                TreeViewItem itemJoe = new TreeViewItem();
                itemJoe.DataContext = new Person() { Name = "Joe", Age = 15 }; ;
                itemSally.Items.Add(itemJoe);
    
                _treeView.Items.Add(itemBob);
                _treeView.Items.Add(itemSally);
            }
        }
    
        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
    
  • kumar TN
    kumar TN over 14 years
    Both your solutions work. Sorry for taking so long to get back to you. I ended up not using a tree in the end, instead implemented a custom hierarchical listbox.
  • Yisroel M. Olewski
    Yisroel M. Olewski about 12 years
    Hooray for Matt! just what i needed (the second solution)