【问题标题】:TreeView template for a tree with circular type reference具有循环类型引用的树的 TreeView 模板
【发布时间】:2012-01-08 23:04:56
【问题描述】:

我需要显示一个绑定到这种分层对象的树:

public class Node
{
    public string Name
    public List<Connector> Connector;
}

public class Connector
{
    public string Name
    public List<Node> TrueChildren;
}

所以一个节点的实际子节点在另一个对象中。

不能让 TreeView 模板使用它。好像我需要循环模板,这在 WPF 中是不可能的。我觉得我错过了一些明显的东西。

【问题讨论】:

  • 你将如何在TreeView呈现这种循环关系?
  • Node 的实例都不同。 n1.Connector(c1,c2,c3) 其中 c1 = (n2,n3), c2 = (n3), c3 = (n4,n5,n6) 其中 n2.Connector(c4,c5)... 等等...值不是循环的。

标签: c# wpf c#-4.0


【解决方案1】:

这不一定是循环的,只有在 Connector.Children 包含对当前节点路径上更高节点的引用时它才是循环的(甚至应该可以使用虚拟化以某种方式处理)。

通常您只需要在TreeView 的资源中创建两个HierarchicalDataTemplates,而不需要任何x:Key,而是将DataType 设置为相应的类型。

<TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:Node}"
                              ItemsSource="{Binding Connector}">
        <TextBlock Text="{Binding Name}"/>
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type local:Connector}"
                              ItemsSource="{Binding TrueChildren}">
        <TextBlock Text="{Binding Name}"/>
    </HierarchicalDataTemplate>
<TreeView.Resources>

(在DataType 中使用x:Type 很重要,如果您想知道为什么阅读property reference

【讨论】:

  • 你是对的。我的错误是我将这两个模板放入 window.resource 并尝试按名称绑定它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多