I\'m studying some paid grid components and they have a pretty cool \"Bound Column\" technique:
It's not a trivial solution, you should to understand how Blazor works with components. Basically, the way, is to register children MyColumn "templates" on outer MyGrid component, then, render grid dynamically with a bit of reflection. Below I post the recipe ready for copy-paste, test and learn.
dotnet new blazorserver
Pages/MyColumn.razor component:@code {
[Parameter]
public string Field { get; set; }
[CascadingParameter]
private MyGrid Parent { get; set; }
protected override void OnInitialized()
{
base.OnInitialized();
Parent.AddColumn(this); //register child into parent
}
}
Pages/MyGrid.razor component:
@ChildContent
@foreach (var item in DataSource)
{
@RowItem(item)
}
@code {
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public IEnumerable
// Here the function to create each row dynamically:
private RenderFragment RowItem(object row)
{
int i = 0;
return b => // create dynamically
{
b.OpenElement(++i, "tr");
foreach(var column in Columns)
{
b.OpenElement(++i, "td");
var val = row.GetType().GetProperty(column.Field)
.GetValue(row, null).ToString();
b.AddContent(++i,val);
b.CloseElement();
}
b.CloseElement();
};
}
}
Pages/FetchData.razor@page "/fetchdata"
@using s.Data
@inject WeatherForecastService ForecastService
Weather forecast
This component demonstrates fetching data from a service.
@if (forecasts == null)
{
Loading...
}
else
{
}
@code {
private WeatherForecast[] forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}
}