aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Render custom Element

Open hungdluit opened this issue 8 years ago • 2 comments

protected override void BuildRenderTree(RenderTreeBuilder builder)
{
          base.BuildRenderTree(builder);

            builder.OpenElement(0, "div");
            BuildContentRenderTree(builder);
            builder.CloseElement();
 }

 protected virtual void BuildContentRenderTree(RenderTreeBuilder builder)
 {
            if (ChildContent != null)
            {
                ChildContent(builder);
            }
   }
@page "/usercontrolsample"

<UserControl>
    <a>This is a User Control</a>
</UserControl>

Result:

image

I'm following same samples on the internet. But it does not work in my case. I think 'div' should be rendered instead of 'usercontrol'

hungdluit avatar May 06 '18 16:05 hungdluit

From what I understand, instead of calling the RenderFragment delegate yourself, you are supposed to call AddContent(int, RenderFragment), as in the code below:

protected override void BuildRenderTree(RenderTreeBuilder builder)
{
    base.BuildRenderTree(builder);

    builder.OpenElement(0, "div");
    builder.AddContent(1, ChildContent);
    builder.CloseElement();
 }

This way, you're letting the RenderTreeBuilder manage its state correctly. What likely happened in your case, is that the ChildContent delegate messed up the sequence numbering when you called it by yourself (because it can't know about your own sequence numbers), which confused Blazor during rendering.

I've actually used AddContent for that there so I'm pretty confident that it works. 🙂

hexawyz avatar May 07 '18 22:05 hexawyz

thanks @GoldenCrystal , that helps me alot :)

hungdluit avatar May 08 '18 01:05 hungdluit