Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override a render fragment in a base component in blazor

I am using the Blazorise DataGrid and I wanted to make a custom DataGridColumn where DisplayTemplate is pre set to a template however I cant figure out how I am supposed to set the DisplayTemplate if I derive from the DataGridColumn. I started with this

   @typeparam TItem
   @inherits DataGridColumn<TItem>

But then I had no clue how to set the DisplayTemplate render fragment to a razor snippet.

I also tried instead just making a component that had a DataGridColumn in it and referenced that in my DataGrid but then the column was always at the end regardless of where I put it in the DataGrid.

I am probably barkign up the wrong tree but I have a lot of classes that implement interfaces where I will always want to set the DisplayTemplate the same for a specific column in any data grid for any type that implements that interface. So it seemed reasonable to make a DataGridColumn derived type for that purpose.

like image 803
Digital Powers Avatar asked Nov 07 '22 09:11

Digital Powers


1 Answers

You can fill DisplayTemplate in your derived class within the code section:

@typeparam TItem
@inherits DataGridColumn<TItem>

@{
    base.BuildRenderTree(__builder);
}


@code { 
    protected override void OnInitialized()
    {
        base.OnInitialized();
        this.DisplayTemplate = (TItem item) => @<CustomDisplayTemplate T="TItem" Item="@item" />;
    }
}

For this to work you'll want to define a separate Blazor component called CustomDisplayTemplate:

@typeparam T
<h2>@Item.ToString()</h2>

@code {
    [Parameter]
    public T Item { get; set; }
}
like image 139
Marco Avatar answered Nov 12 '22 16:11

Marco