RadzenTree with data-binding and children of different type

Hi! I want to bind RadzenTree to a tree structure with different node types derived from the same base type:

<RadzenTree Data="@data">
    <RadzenTreeLevel TextProperty="Name" ChildrenProperty="Children" />
</RadzenTree>

@code{
    public class TreeNodeViewModel
    {
        public string? Name { get; set; }

        public List<TreeNodeViewModel> Children { get; set; }
    }

    public class FolderNodeViewModel : TreeNodeViewModel
    {

    }

    public class FileNodeViewModel : TreeNodeViewModel
    {

    }

    public List<TreeNodeViewModel> data = new()
        {
            new TreeNodeViewModel
            {
                Name = "RootFolder",
                Children = new List<TreeNodeViewModel>
                {
                    new FolderNodeViewModel { Name = "SubFolder"},
                    new FileNodeViewModel { Name = "SubFile"}
                }
            }
        };
}

This code doesn't work with exception "Error: System.InvalidCastException: Unable to cast object of type 'FileNodeViewModel' to type 'FolderNodeViewModel'.". Is it possible to achieve my goal with current RadzenTree implementation?

Hi @p.ivanov,

Try using the Text property of RadzenTreeLevel:

<RadzenTree Data="@data">
    <RadzenTreeLevel Text=@(node => ((TreeNodeViewModel)node).Name) ChildrenProperty="Children" />
</RadzenTree>

At the moment RadzenTree generates a getter for the text once and it fails with the cast exception because the second item has a different type.

1 Like