Sherlock
Sherlock

Reputation: 5627

WPF TreeView parent node binding

I have the following classes -

public class A : INotifyPropertyChanged
{
    public string Name { get; set; }
    public ObservableCollection<Child> Children { get; set; }

    ...
}

public class Child : INotifyPropertyChanged
{
    public string InstanceName { get; set; }

    ...
}

And here is my TreeView XAML -

<TreeView ItemsSource="{Binding ListOfClassA}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
            <TextBlock Text="{Binding Path=InstanceName}"/>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

In this case, the parent class A name is not displayed. How can I show the Name property on class A as well as the InstanceName property on the Child class.

Upvotes: 2

Views: 1184

Answers (1)

Dmitry
Dmitry

Reputation: 2052

In your code

<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
    <TextBlock Text="{Binding Path=InstanceName}"/>
</HierarchicalDataTemplate>

Is actually the template for your A class. It should be:

<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
    <HierarchicalDataTemplate.ItemTemplate>
        <HierarchicalDataTemplate>
            <!-- this is how Child is visualised-->
            <TextBlock Text="{Binding Path=InstanceName}"/>
        </HierarchicalDataTemplate>
    </HierarchicalDataTemplate.ItemTemplate>
    <!-- this is how A is visualised-->
    <TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>

For better code visibility you can write them in resource section as two separate templates:

<HierarchicalDataTemplate x:Key="Child_template">
     <!-- this is how Child is visualised-->
     <TextBlock Text="{Binding Path=InstanceName}"/>
</HierarchicalDataTemplate>

<HierarchicalDataTemplate x:Key="A_template" ItemsSource="{Binding Path=Children}"
    ItemTemplate="{StaticResource Child_template}">
    <!-- this is how A is visualised-->
    <TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>

Hope this helps. For reference: http://msdn.microsoft.com/en-us/library/dd759035(v=vs.95).aspx

Upvotes: 1

Related Questions