asp.net-coreblazordevexpressblazor-server-sideasp.net-core-5.0

How to pass a RenderFragement<object> Template to a Blazor component


I'm stucking on one special thing where I try to pass an object of RenderFragment to a dynamically generated component.

I considered this sample from Devexpress https://docs.devexpress.com/Blazor/401753/common-concepts/customize-and-reuse-components

<DxFormLayout>
    <DxFormLayoutTabPages>
        @renderLayoutTabPage()
    </DxFormLayoutTabPages>
</DxFormLayout>

@code {
    private RenderFragment renderLayoutTabPage() {
        RenderFragment item = b => {
            b.OpenComponent<DxFormLayoutTabPage>(0);
            b.AddAttribute(1, "Caption", "My tab");
            b.AddAttribute(2, "ChildContent", (RenderFragment)((tabPageBuilder) => {
                tabPageBuilder.OpenComponent<DxFormLayoutItem>(0);
                tabPageBuilder.AddAttribute(1, "Caption", "DynLayoutItem");
                tabPageBuilder.AddAttribute(2, "ColSpanMd", 6);
                tabPageBuilder.AddAttribute(5, "Template", (RenderFragment<Object>)((context) => ((itemTemplate) => {
                    itemTemplate.OpenComponent<DxTextBox>(0);
                    itemTemplate.AddAttribute(1, "Text", text);
                    itemTemplate.CloseComponent();
                })));
                tabPageBuilder.CloseComponent();
            }));
            b.CloseComponent();
        };
        return item;
    }
}

So this is the way they are building a complete new ChildContent Fragment.

my razor file looks like:

    [Parameter] RenderFragment<object> DisplayTemplate {get;set;} //pass this Fragement to the dynamic component
    
    protected override void OnInitialized()
    {
      ...        
      b.AddAttribute(3, nameof(DxDataGridColumn.DisplayTemplate), (RenderFragment<Object>)((context) => ((itemTemplate) =>
                                {
                                    itemTemplate.AddContent<object>(0, DisplayTemplate, context);
                                })));
       ...
    }

When I run this, the DisplayTemplate does not get rendered. I only can see the type string

Microsoft.AspNetCore.Components.RenderFragment`1[System.Object]

What I'm doing wrong here?


Solution

  • In my Component I was using this pattern

    <MyComponent>
      <DisplayTemplate>
        @DisplayTemplate
      </DisplayTemplate>
    <MyComponent>
    

    The only way it works correct is to use the Attributes directly:

    <MyComponent DisplayTemplate"@DisplayTemplate" />