Adding nodes to node as a WPF tree

In Visual C ++ / MFC, we used to add a node to the tree, and then, referring to the node, we could add children to the parent node. However, in WPF there is no such thing as I see. I am confused how to add child / children in node?

Any help would be appreciated.

It seems 2 people know MVVM already!

The solution is given below by Tim.

+5
source share
4 answers

A quick google search wpf treeview found some great articles on how to properly use tree structures in WPF.

Example 1: http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode

Example 2: http://www.c-sharpcorner.com/uploadfile/mahesh/treeview-in-wpf/

- , MVVM- .

+8

OP , , , , .

, , - , WPF. :

var item = new TreeViewItem(); 
myTreeView.Items.Add(item); 
var subItem1 = new TreeViewItem(); 
var subItem2 = new TreeViewItem(); 
item.Items.Add(subItem1); 
item.Items.Add(subItem2);

.

Header TreeViewItem Tag , .

, HierarchicalDataTemplates . , (TreeViewItems) .

HierarchicalDataTemplates, , . MVVM .

+10

Create your model as follows

public class WrappedNode
{
    public string Name { get; set; }
    public ObservableCollection<WrappedNode> Nodes { get; set; }

    public WrappedNode()
    {
        Nodes = new ObservableCollection<WrappedNode>();
    }        
}

Node list you want to associate with treeview

private ObservableCollection<WrappedNode> _nodeList;
public ObservableCollection<WrappedNode> NodeList
{
    get { return _nodeList; }
    set
    {
        _nodeList = value;
        RaisePropertyChanged(() => NodeList);
    }
}

And in xaml:

    <TreeView Grid.Row="1"
              ItemsSource="{Binding NodeList}">
        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type scnvm:WrappedNode}" ItemsSource="{Binding Nodes}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>

If you want a node to have children, just add a node child to the node's Nodes property

0
source

To add an item as a parent:

var item = new TreeViewItem();
item.Header = "First Element";
tree.Items.Add(item); //tree is your treeview

To add an item as a child of a specific item:

var subItem = new TreeViewItem();
subItem.Header = "Subitem";
var parent = tree.SelectedItem as TreeViewItem;  // Checking for selected element
parent.Items.Add(subItem);
0
source

All Articles