【问题标题】:WPF TreeView parent node bindingWPF TreeView 父节点绑定
【发布时间】:2014-04-11 22:46:49
【问题描述】:

我有以下课程 -

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 的名称。如何在A 类上显示Name 属性以及Child 类上的InstanceName 属性。

【问题讨论】:

  • 您的属性需要公开
  • 他们在现实生活中是公开的,我会进行编辑,这样会更清楚。

标签: c# wpf xaml treeview


【解决方案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

【讨论】:

  • 嗨迪迪埃 - 感谢您的回答。我收到一个错误:“在使用 ItemsSource 之前,项目集合必须为空。”使用此代码时。我需要做一些额外的改变吗?
  • 这意味着您手动添加了一些项目。可能您使用一些 csharp 在某处广告项目。您不能同时按代码和 ItemsSource 属性对子项进行广告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 2010-09-19
相关资源
最近更新 更多