Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 289559
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T05:55:04+00:00 2026-05-12T05:55:04+00:00

I’m adding TreeViewItems manually in code behind and would like to use a DataTemplate

  • 0

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; }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T05:55:04+00:00Added an answer on May 12, 2026 at 5:55 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 141k
  • Answers 141k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer System.Activator.CreateInstance(Type.GetType(className)) The problem, however, is that C# 3.0 is a… May 12, 2026 at 8:09 am
  • Editorial Team
    Editorial Team added an answer This SO post answers your question: UIkeyboard type May 12, 2026 at 8:09 am
  • Editorial Team
    Editorial Team added an answer mocks are bad in cucumber scenarios - they're almost kind… May 12, 2026 at 8:09 am

Related Questions

I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I am currently running into a problem where an element is coming back from
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.