Articles in this section
Category / Section

How to update checkbox state programmatically in Xamarin.Forms TreeView (SfTreeView)

1 min read

The check box state of the TreeViewNode  can be updated programmatically in Xamarin.Forms SfTreeView.

C#

The GetCheckedNodes method returns all the checked nodes. In the SfTreeView.Loaded event, update the parent or child node’s checked state of the checked nodes. Set the SfTreeView.CheckBoxMode to Recursive, to update the checked state on UI interaction.

public class TreeViewBehavior : Behavior<SfTreeView>
{
    SfTreeView TreeView;
 
   protected override void OnAttachedTo(SfTreeView bindable)
    {
        base.OnAttachedTo(bindable);
 
        TreeView = bindable;
        TreeView.Loaded += TreeView_Loaded;
    }
 
    private void TreeView_Loaded(object sender, TreeViewLoadedEventArgs e)
    {
        UpdateCheckBoxState();
        TreeView.CheckBoxMode = CheckBoxMode.Recursive;
    }
 
    private void UpdateCheckBoxState()
    {
        var checkedNodes = TreeView.GetCheckedNodes();
        foreach (var node in checkedNodes)
        {
            if (node.ParentNode == null && node.HasChildNodes)
            {
                //Update child nodes based on parent's checked state.
                SetChildChecked(node);
            }
 
            else
            {
                //Update parent node based on child's checked state.
                SetParentChecked(node);
            }
        }
    }
 
    private void SetChildChecked(TreeViewNode node)
    {
        foreach (var child in node.ChildNodes)
        {
            child.IsChecked = true;
            if (child.HasChildNodes)
            {
                SetChildChecked(child);
            }
        }
    }
 
    private void SetParentChecked(TreeViewNode node)
    {
        if (node.ParentNode == null) return;
 
        if (node.ParentNode.ChildNodes.All(x => x.IsChecked == true))
            node.ParentNode.IsChecked = true;
 
        else node.ParentNode.IsChecked = null;
 
        if(node.ParentNode != null)
        {
            SetParentChecked(node.ParentNode);
        }
    }
}

You can refer the check box state behavior in our user guide documentation.

View sample in GitHub

Checked state Xamarin.Forms SfTreeView

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please  to leave a comment
Access denied
Access denied