开发者

Display "root" node in TreeView

开发者 https://www.devze.com 2023-03-12 05:04 出处:网络
How to display the \"root\" in TreeView? Do I need to createa a special HierarchicalDataTemplate for the root?

How to display the "root" in TreeView?

Do I need to create a a special HierarchicalDataTemplate for the root?

This is my code:

<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.Ch开发者_开发百科ildren.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;
    }

}


If you want a root you need to specify an ItemsSource with only one item in it, the root node, it has to be an IEnumerable, the node itself cannot be the source.

e.g.

treeView.ItemsSource = new [] { rootNode };


Use a converter:

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();
    }
}

In XAML:

<TreeView ItemsSource="{Binding Path=RootNode,Converter={StaticResource rootConv}}" />
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号