IgbGrid に表示するデータや列定義情報を動的に切り替える場合は、
- 列定義情報を別途持つ。
- 列定義情報をもとに foreach などを使用して IgbColumn を生成する。
- 表示データと列定義情報が切り替わるタイミングで Blazor フレームワークに対して再描画を促す。
で可能です。
1. 列情報を別途持つ
表示するデータのクラスのプロパティ名とその表示テキストを保持するクラスを定義します。
// Data\ColumnConfiguration.cs
public class ColumnConfiguration
{
public String PropertyName { get; set; } = "";
public String DisplayText { get; set; } = "";
public ColumnConfiguration()
{
}
}
2. 列定義情報をもとに foreach などを使用して IgbColumn を生成する
@* App.razor *@
<IgbGrid ... Data="@GridDataSource">
@if (GridColumnConfigurations != null)
{
@foreach (var columnConfig in GridColumnConfigurations)
{
<IgbColumn Field="@columnConfig.PropertyName" Header="@columnConfig.DisplayText" />
}
}
</IgbGrid>
@code {
private object[]? GridDataSource = null;
private ColumnConfiguration[]? GridColumnConfigurations = null;
...
}
3. 表示データと列定義情報が切り替わるタイミングで Blazor フレームワークに対して再描画を促す
@* App.razor *@
<IgbGrid @key="Counter" ... Data="@GridDataSource" ...>
@if (GridColumnConfigurations != null)
{
@foreach (var columnConfig in GridColumnConfigurations)
{
<IgbColumn Field="@columnConfig.PropertyName" Header="@columnConfig.DisplayText" />
}
}
</IgbGrid>
@code {
private int Counter = 0;
...
// OnCustomersとOnProductsは表示データと列定義情報を切り替えたいタイミングで呼び出されるメソッドという想定
private async Task OnCustomers()
{
// Customersのデータと列情報を取得し、IgbGridのデータとして設定する。
(GridDataSource, GridColumnConfigurations) = await PeopleAndProductsDS.GetCustomersAndConfigurationsAsync();
// IgbGridにBlazorの@key属性のディレクティブを追加し、
// その値であるCounterの値をインクリメントすることで、
// Blazorフレームワークに再描画を促す。
// https://learn.microsoft.com/ja-jp/aspnet/core/blazor/components/element-component-model-relationships?view=aspnetcore-7.0
Counter++;
}
private async Task OnProducts()
{
// 同様
// Productのデータと列情報を取得し、IgbGridのデータとして設定する。
(GridDataSource, GridColumnConfigurations) = await PeopleAndProductsDS.GetProductsAndConfigurationsAsync();
Counter++;
}
}
実行結果
顧客データ表示時

製品データ表示時
