CRUD Operations in WinUI TreeView

14 Apr 20214 minutes to read

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

Add nodes

TreeView allows user to add new node directly by adding new data object to underlying collection in bound mode and by adding TreeViewNode to 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

TreeView provides built-in support to delete the selected nodes in user interface (UI) by pressing 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 node directly in 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).Orders.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 of ItemDeleting event. This event occurs when the node is being deleted using 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 remove the nodes through SfTreeView.SelectedItem property in ItemDeleted event. This event occurs after the node is deleted using 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

Treeview allows user to modify the data in a node by editing.