Blazor Render Tree Builder Not Rendering ChildContent

  Kiến thức lập trình

I have tried to find a solution to this issue with no success.

I have created my own text control that wraps MudBlazor’s MudText and MudLink controls for rendering text or links to create consistency when managing responsive flows.

Originally, I had a very complex nesting structure in my razor file, and my @ChildContent was rendering correctly. I wanted to simplify it, and use the RenderTree builder to build my control dynamically. When I did builder.AddContent(4,ChildContent), the control rendered, but none of the associated text in the child content came through.

Here’s the relevant content in the code behind file:

[Parameter]
public RenderFragment? ChildContent { get; set; }

private RenderFragment RenderContent(Typo typo) => builder =>
{
    if (Align.HasValue && _isShowLink)
    {
        builder.OpenComponent<MudText>(0);
        builder.AddAttribute(1, "Align", Align.Value);
        builder.AddContent(2, RenderTextOrComponent(typo));
        builder.CloseComponent();
    }
    else
    {
        builder.AddContent(1, RenderTextOrComponent(typo));
    }
};

private RenderFragment RenderTextOrComponent(Typo typo) => builder =>
{
    var componentType = _isShowLink ? typeof(MudLink) : typeof(MudText);
    builder.OpenComponent(0, componentType);

    if (!string.IsNullOrWhiteSpace(Class))
    {
        builder.AddAttribute(1, "Class", Class);
    }

    if (_isShowLink)
    {
        builder.AddAttribute(2, "Href", Href);
        builder.AddAttribute(3, "Typo", typo);
    }
    else
    {
        if (Align.HasValue)
        {
            builder.AddAttribute(2, "Align", Align);
        }

        builder.AddAttribute(3, "Typo", typo);
    }

    builder.AddContent(4, ChildContent);
    builder.CloseComponent();
};

From everything I’ve seen, this should be working. If I include @ChildContent on the razor page, it will render the text included in the child content appropriately.

What am I missing?

LEAVE A COMMENT