Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The simplest way is to use bindings and <code>HierarchicalDataTemplate</code>. Declare a class with your data :</p> <pre><code>class Item : INotifyPropertyChanged { public Item() { this.Children = new ObservableCollection&lt;Item&gt;(); } public event PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public ObservableCollection&lt;Item&gt; Children { get; private set; } } </code></pre> <p>And define a <code>HierarchicalDataTemplate</code> for this type :</p> <pre><code>&lt;HierarchicalDataTemplate DataType="{x:Type my:Item}" ItemsSource="{Binding Items}"&gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/HierarchicalDataTemplate&gt; </code></pre> <p>Now you just need to bind the <code>ItemsSource</code> of the <code>TreeView</code> to your collection of top-level items, and the tree nodes will be constructed automatically. If you need to add (or remove) a node, just add an item to (or remove it from) the parent collection</p> <p>For this example, I used a single item type, but if you have several types to display in the <code>TreeView</code> you will need to define a <code>HierarchicalDataTemplate</code> for each. For leaf nodes (nodes with no children), you can just use a regular <code>DataTemplate</code></p>
 

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