This example demonstrates how you can use a dictionary to configure the Blazor Grid component. This technique allows you to configure multiple components based on one options set.
Create a ComponentBase class descendant that accepts a data source, grid columns, and grid settings stored in a dictionary. In the created class, configure the Grid component at runtime as follows:
public class MyGrid<T> : ComponentBase
{
[Parameter]
public IEnumerable<T> Data { get; set; }
[Parameter]
public RenderFragment ChildContent { get; set; }
[Parameter]
public Dictionary<string, object> Settings { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder) {
builder.OpenComponent<DxGrid>(0);
builder.AddAttribute(1, "Data", (object)Data);
builder.AddAttribute(2, "Columns", ChildContent);
if (Settings != null) {
builder.AddMultipleAttributes(3, Settings);
//OR
//int seq = 3;
//foreach (var item in Settings) {
// builder.AddAttribute(seq++, item.Key, item.Value);
//}
}
builder.CloseComponent();
}
}
Create a dictionary that stores setting names and values. Assign this dictionary to the corresponding component parameter to create and configure the Grid:
<MyGrid Data="Forecasts" Settings="InputAttributes" >
<DxGridCommandColumn Width="150px" />
<DxGridDataColumn FieldName="@nameof(WeatherForecast.Date)" />
<DxGridDataColumn FieldName="@nameof(WeatherForecast.TemperatureC)" />
<DxGridDataColumn FieldName="@nameof(WeatherForecast.TemperatureF)" />
<DxGridDataColumn FieldName="@nameof(WeatherForecast.Summary)" />
</MyGrid>
@code {
public List<WeatherForecast> Forecasts { get; set; }
public Dictionary<string, object> InputAttributes { get; set; } =
new Dictionary<string, object>() {
{ "EditMode", GridEditMode.EditRow},
{ "PageSize", 5 },
{ "ShowFilterRow", false },
{ "PagerVisible" , false },
{ "ShowGroupPanel", true }
};
protected override async Task OnInitializedAsync() {
base.OnInitialized();
WeatherForecast[] data = await ForecastService.GetForecastAsync(DateTime.Now);
Forecasts = data.ToList();
}
}
(you will be redirected to DevExpress.com to submit your response)