Unplanned
Last Updated: 15 Aug 2024 11:56 by Jerome
Jerome
Created on: 15 Aug 2024 11:56
Category: TreeView
Type: Bug Report
3
TreeView checkboxes lose their checked state when adding or removing items

The TreeView resets the checkbox state of its items when the app adds or removes a node to the component datasource.

A possible workaround is to reset the object reference of the CheckedItems parameter.

The following test page with a workaround is a modified version of TreeView - Refresh Data - Observable Data.

@using System.Collections.ObjectModel

<TelerikButton OnClick="@AddItem">Add Item</TelerikButton>

<TelerikButton OnClick="@RemoveItem">Remove Item</TelerikButton>

<p>
    TreeViewCheckedItems Count: @TreeViewCheckedItems.Count()
    <br />
    <label><TelerikCheckBox @bind-Value="@ApplyWorkaround" /> Apply Workaround</label>
</p>

<TelerikTreeView Data="@TreeViewData"
                 CheckBoxMode="@TreeViewCheckBoxMode.Multiple"
                 @bind-CheckedItems="@TreeViewCheckedItems" />

@code {
    private IEnumerable<object> TreeViewCheckedItems { get; set; } = new List<TreeItem>();
    private ObservableCollection<object> TreeViewData { get; set; } = new ObservableCollection<object>();

    private int LastId { get; set; }
    private bool ApplyWorkaround { get; set; }

    private void AddItem()
    {
        TreeViewData.Add(
            new TreeItem
            {
                Id = ++LastId,
                Text = $"Item {LastId}",
            });

        if (ApplyWorkaround)
        {
            TreeViewCheckedItems = new List<object>(TreeViewCheckedItems);
        }

    }

    private void RemoveItem()
    {
        if (TreeViewData.Count > 1)
        {
            TreeViewData.Remove(TreeViewData.Last());

            if (ApplyWorkaround)
            {
                TreeViewCheckedItems = new List<object>(TreeViewCheckedItems);
            }
        }
    }

    protected override void OnInitialized()
    {
        TreeViewData = new ObservableCollection<object>() {
            new TreeItem()
            {
                Id = ++LastId,
                Text = $"Item {LastId}"
            }
        };

        TreeViewCheckedItems = new List<object>() { TreeViewData.First() };
    }
    public class TreeItem
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string Text { get; set; } = string.Empty;
        public bool HasChildren { get; set; }
    }
}

 

asdf

0 comments