WPF TreeView父节点绑定

时间:2014-04-11 22:46:49

标签: c# wpf xaml treeview

我有以下课程 -

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

    ...
}

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

    ...
}

这是我的TreeView XAML -

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

在这种情况下,不显示父类A名称。如何在Name课上显示A属性以及InstanceName类的Child属性。

1 个答案:

答案 0 :(得分:1)

在您的代码中

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

实际上是A类的模板。它应该是:

<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>

为了获得更好的代码可见性,您可以将它们作为两个单独的模板在资源部分中编写:

<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>

希望这会有所帮助。 供参考:http://msdn.microsoft.com/en-us/library/dd759035(v=vs.95).aspx