CRUD Operations in WinUI TreeView

17 Jul 20264 minutes to read

The TreeView listens and responds to the CRUD operations such as add, delete, and data update (property change) at runtime. It also supports editing and delete by pressing the Delete key.

Add nodes

The TreeView allows the user to add a new node directly by adding a new data object to the underlying collection in bound mode and by adding a TreeViewNode to the Nodes collection in unbound mode.

// For bound mode
(sfTreeView.DataContext as ViewModel).Countries.Add(new Country() { Name = "Germany"});

// For Unbound mode
sfTreeView.Nodes.Add(new TreeViewNode(){ Content = "Germany" });

Delete nodes

The TreeView provides built-in support to delete the selected nodes in the user interface (UI) by pressing the Delete key. You can enable the deleting support by setting the SfTreeView.AllowDeleting property to true.

<treeView:SfTreeView  
                x:Name="sfTreeView" 
				AllowDeleting="True"
				ChildPropertyName="Files"
                ItemsSource="{Binding Countries}"/>
sfTreeView.AllowDeleting = true;

You can delete a node directly in the underlying collection also using Remove() or RemoveAt(int index).

//For Bound mode
(sfTreeView.DataContext as ViewModel).Countries.Remove(sfTreeView.SelectedItem as Country);

// OR
(sfTreeView.DataContext as ViewModel).Countries.RemoveAt(2);

// For Unbound mode
sfTreeView.Nodes.Remove(sfTreeView.Nodes[0]);

//OR
sfTreeView.Nodes.RemoveAt(2);

Event customization

Delete selected nodes conditionally

You can cancel the node deletion by using the ItemDeletingEventArgs.Cancel property of the ItemDeleting event. This event occurs when the node is being deleted using the Delete key. You can skip certain nodes when deleting more than one node by removing items from ItemDeletingEventArgs.Nodes.

sfTreeView.ItemDeleting += TreeView_ItemDeleting;

private void TreeView_ItemDeleting (object sender, ItemDeletingEventArgs e)
{
    var nodeCollection = e.Nodes.ToList();
    foreach (var node in nodeCollection)
    {
        var country = node.Content as Country;
        if (country != null)
        {
            if (country.Name == "Brazil")
                e.Cancel = true;
            else if (country.Name == "India")
                e.Nodes.Remove(node);
        }        
    }
}

Reset selection after deleting the selected node

You can handle the selection after removing the nodes through the SfTreeView.SelectedItem property in the ItemDeleted event. This event occurs after the node is deleted using the Delete key.

sfTreeView.ItemDeleted += TreeView_ItemDeleted;

private void TreeView_ItemDeleted (object sender, ItemDeletedEventArgs e)
{
    if(sfTreeView.Nodes.Count > 0)
    {
        sfTreeView.SelectedItem = sfTreeView.Nodes[0].Content;
    }
}

Modify nodes

The TreeView allows users to modify the data of a node through its editing functionality. For more information, refers to the Editing documentation.