anderi
anderi

Reputation: 777

Display "root" node in TreeView

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.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;
    }

}

Upvotes: 1

Views: 5871

Answers (2)

brunnerh
brunnerh

Reputation: 184574

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

Upvotes: 4

Mitch
Mitch

Reputation: 22251

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}}" />

Upvotes: 3

Related Questions