If the application expands TreeView items programmatically, and then the user tries to select multiple items, an exception will occur.
The issue is a regression that occurred in version 3.0.0. A possible workaround is to Rebind()
the TreeView with a small delay after programmatic item expansion.
<TelerikTreeView @ref="@TreeViewRef"
Data="@FlatData"
@bind-ExpandedItems="@ExpandedItems"
SelectionMode="@TreeViewSelectionMode.Multiple"
SelectedItems="@SelectedItems"
SelectedItemsChanged="@((IEnumerable<object> items) => SelectedItemsHandler(items))" />
<TelerikButton OnClick="@ExpandAll">Expand All</TelerikButton>
<TelerikButton OnClick="@CollapseAll">Collapse All</TelerikButton>
@code {
public TelerikTreeView TreeViewRef { get; set; }
public IEnumerable<TreeItem> FlatData { get; set; }
public IEnumerable<object> SelectedItems { get; set; } = new List<object>();
public IEnumerable<object> ExpandedItems { get; set; } = new List<object>();
async Task ExpandAll()
{
ExpandedItems = FlatData.Where(x => x.HasChildren == true);
await Task.Delay(1);
TreeViewRef.Rebind();
}
void CollapseAll()
{
ExpandedItems = new List<object>();
SelectedItems = new List<object>();
}
void SelectedItemsHandler(IEnumerable<object> items)
{
SelectedItems = items;
}
protected override async void OnInitialized()
{
FlatData = LoadFlat();
}
int TreeLevels { get; set; } = 3;
int ItemsPerLevel { get; set; } = 3;
int IdCounter { get; set; } = 1;
List<TreeItem> LoadFlat()
{
List<TreeItem> items = new List<TreeItem>();
PopulateTreeItems(items, null, 1);
return items;
}
void PopulateTreeItems(List<TreeItem> items, int? parentId, int level)
{
for (int i = 1; i <= ItemsPerLevel; i++)
{
var itemId = IdCounter++;
items.Add(new TreeItem()
{
Id = itemId,
Text = $"Level {level} Item {i} Id {itemId}",
ParentId = parentId,
HasChildren = level < TreeLevels
});
if (level < TreeLevels)
{
PopulateTreeItems(items, itemId, level + 1);
}
}
}
public class TreeItem
{
public int Id { get; set; }
public string Text { get; set; }
public int? ParentId { get; set; }
public bool HasChildren { get; set; }
}
}