Digital Powers
Digital Powers

Reputation: 470

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.

Upvotes: 6

Views: 1740

Answers (1)

Marco
Marco

Reputation: 840

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; }
}

Upvotes: 2

Related Questions