WPF TreeView Data Binding


This entry is part 3 of 6 in the series WPF TreeView

As WPF Tutorial says in their website post TreeView, data binding and multiple templates “The WPF TreeView supports data binding, as pretty much all other WPF controls do, but because the TreeView is hierarchical in nature, a normal DataTemplate often won’t suffice. Instead, we use the HierarchicalDataTemplate, which allows us to template both the tree node itself, while controlling which property to use as a source for child items of the node.”

Below is the XAML code.

<Window x:Class="TreeViewDataBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TreeViewDataBinding"
        xmlns:self="clr-namespace:TreeViewDataBinding"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="TreeViewDataBinding" Height="250" Width="400">
    <Grid>
        <TreeView Name="trvMenu">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate DataType="{x:Type self:MenuItem}" ItemsSource="{Binding Items}">
                    <TextBlock Text="{Binding Title}" />
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>
</Window>

Here is the code-behind.

using System.Collections.ObjectModel;
using System.Windows;
namespace TreeViewDataBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MenuItem root = new MenuItem() { Title = "Menu" };
            root.Items.Add(new MenuItem() { Title = "subM" });

            MenuItem childItem1 = new MenuItem() { Title = "Child item #1" };
            childItem1.Items.Add(new MenuItem() { Title = "Child item #1.1" });
            childItem1.Items.Add(new MenuItem() { Title = "Child item #1.2" });
            root.Items.Add(childItem1); 

            root.Items.Add(new MenuItem() { Title = "Child item #2" });

            trvMenu.Items.Add(root);
        }
    }
    public class MenuItem
    {
        public MenuItem()
        {
            this.Items = new ObservableCollection<MenuItem>();
        }

        public string Title { get; set; }

        public ObservableCollection<MenuItem> Items { get; set; }
    }
}

Series Navigation<< WPF TreeView HeadersWPF TreeView Multiple Templates >>