Search This Blog

Tuesday, November 12, 2013

WPF TreeView HierarchicalDataTemplate

WPF > ControlsItemsControl > TreeView > HierarchicalDataTemplate 

WPF TreeView HierarchicalDataTemplate binding to object with multiple child collections



XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Background="#FFF3EEEE" Loaded="Window_Loaded"
     xmlns:local="clr-namespace:WpfApplication1">

    <TreeView x:Name="tv" HorizontalAlignment="Left" Height="320" VerticalAlignment="Top" Width="517" >
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:Person}" ItemsSource="{Binding Persons}">
                <TextBlock Text="{Binding Title}" />
            </HierarchicalDataTemplate>
       </TreeView.Resources>
    </TreeView>
</Window>

C# Code:
namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    ///

    public class Person
    {
            public Person()
            {
                this.Persons = new ObservableCollection<Person>();
            }

            public string Title { get; set; }
            public ObservableCollection<Person> Persons { get; set; }
    }
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Person root = new Person() { Title = "Manager" };
            Person item1 = new Person() { Title = "Team Leader1" };
            item1.Persons.Add(new Person() { Title = "Emp 1" });
            item1.Persons.Add(new Person() { Title = "Emp 2" });
            root.Persons.Add(item1);
            root.Persons.Add(new Person() { Title = "Admin" });
            tv.ItemsSource = root.Persons; 
        }
    }
}