如何在TreeView中显示“root”?
我是否需要为root创建一个特殊的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;
}
}
答案 0 :(得分:4)
如果你想要一个root,你需要指定一个ItemsSource
只有一个项目,根节点,它必须是IEnumerable
,节点本身不能作为源。
e.g。
treeView.ItemsSource = new [] { rootNode };
答案 1 :(得分:3)
使用转换器:
public class RootTreeviewConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
return new object[] { value };
}
public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在XAML中:
<TreeView ItemsSource="{Binding Path=RootNode,Converter={StaticResource rootConv}}" />