Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing ItemTemplate for a TreeView when adding items in code
    primarykey
    data
    text
    <p>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?</p> <p>XAML</p> <pre><code>&lt;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"&gt; &lt;Grid&gt; &lt;TreeView Name="_treeView"&gt; &lt;TreeView.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;TextBlock Text="{Binding Path=Age}" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/TreeView.ItemTemplate&gt; &lt;/TreeView&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>Behind code</p> <pre><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; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload