gpt4 book ai didi

c# - 在 TreeView 中显示 "root"节点

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:44 29 4
gpt4 key购买 nike

如何在TreeView中显示“根”?

我是否需要为根创建一个特殊的 HierarchicalDataTemplate?

这是我的代码:

<TreeView Margin="0,0,15,0" Name="treeView1" ItemsSource="{Binding Path=Children}">           
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Node}"
ItemsSource="{Binding Path=Children}">
<Border BorderBrush="Black" BorderThickness="1">
<StackPanel>
<TextBlock Margin="10,0,0,0" Text="{Binding Data}"/>
</StackPanel>
</Border>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Node node0 = new Node("Root");
Node node1 = new Node("Node1-1");
Node node12 = new Node("Node1-2");
Node node21 = new Node("Node2-1");
Node node22 = new Node("Node2-2");
Node node31 = new Node("Node3-1");
Node node9 = new Node("Node9");
node12.Children.Add(node21);
node12.Children.Add(node22);
node22.Children.Add(node31);
node1.Children.Add(node9);

node0.Children.Add(node1);
node0.Children.Add(node12);
treeView1.DataContext = node0;

public class Node
{
List<Node> children;
public List<Node> Children
{
get { return children; }
set { children = value; }
}

string data;
public string Data
{
get { return data; }
set { data = value; }
}

public Node()
{
children = new List<Node>();
}

public Node(string data)
: this()
{
this.data = data;
}

}

最佳答案

如果你想要一个根,你需要指定一个只有一个项目的ItemsSource,根节点,它必须是一个IEnumerable,节点本身不能成为来源。

例如

treeView.ItemsSource = new [] { rootNode };

关于c# - 在 TreeView 中显示 "root"节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6307595/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com