Search code examples
blazor

Blazor Renderfragment RenderTreeBuilder Parent / Childs


I use

RenderFragment MyRenderFragment() { 
    return builder => { switch (item.Name) { case .... 

to run components and it works great. Now I want to use this on a parent / childs example but I can't work it out.

For example this one :

<RadzenRadioButtonList @bind-Value=@value TValue="int">
    <Items>
        <RadzenRadioButtonListItem Text="Orders" Value="1" />
        <RadzenRadioButtonListItem Text="Employees" Value="2" />
        <RadzenRadioButtonListItem Text="Customers" Value="3" />
    </Items>
</RadzenRadioButtonList>

I tried this code :

builder.OpenComponent<RadzenRadioButtonList<int>>(0);
builder.AddAttribute(1, "Value", value);
builder.AddAttribute(2, "ValueChanged", EventCallback.Factory.Create<T>(this, async (T e) =>
{
    await ValueChanged.InvokeAsync(e);
}));
builder.AddAttribute(3, "TValue", typeof(int));
builder.AddAttribute(5, "ChildContent", (RenderFragment)((builder2) =>
{
    // I tried with foreach and get data from List<> but not work, tried with singledata but this will not work neither.
    builder2.OpenComponent<RadzenRadioButtonListItem<int>>(6);
    builder2.AddAttribute(7, "Text", "Orders");
    builder2.AddAttribute(8, "Value", 1);
    builder2.CloseComponent();
}
builder.CloseComponent();

But it will not work. Anyone who knows how to use this in parent / childs relations?


Solution

  • In the code you show the RadzenRadioButtonListItem components in a Parameter RenderFragment named Items , not ChildContent.

    //....
    builder.AddAttribute(5, "Items", (RenderFragment)((builder2) =>
    {
        // can reset the numbering here as it's a different Render Frame
        builder2.OpenComponent<RadzenRadioButtonListItem<int>>(0);
        builder2.AddAttribute(1, "Text", "Orders");
        builder2.AddAttribute(2, "Value", 1);
        builder2.CloseComponent();
    }
    /....
    

    You will need a @foreach loop to add the various options.