FlexGrid supports conditional formatting where you can highlight cells in different styling formats based on specific variations in the data. Conditional formatting enables you to analyze the data, detect critical conditions and identify certain data types. The appearance of cells is changed on the basis of weather the specified conditions are true or false.
The FlexGrid implements this feature by creating custom cells using the GridCellFactory class. This class is inherited to create custom cells which are styled based on specific criterion. The cell factory provides complete control over the display of each cell.
In this example, conditional formatting on temperature range for the weather forecast data is applied as shown in the image below.
The following code example demonstrate how to implement conditional formatting in FlexGrid by inheriting GridCellFactory class.
<h3>CellFactoryを使用してスタイル設定します。</h3>
<p>
セル描画用のロジックを実装し、セルのスタイルとコンテンツを変更するには、CellFactoryプロパティを使用します。
GridCellFactoryから継承されたClassオブジェクトを受け入れるCellFactoryプロパティ。
</p>
<FlexGrid ItemsSource="@forecasts" CellFactory="@gridCellFactory"></FlexGrid>
@code {
WeatherForecast[] forecasts;
MyCellFactory gridCellFactory = new MyCellFactory();
//FlexGridのデータ
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}
//セルをスタイル設定するには、カスタムのCellFactoryを作成します
public class MyCellFactory : GridCellFactory
{
public override void PrepareCellStyle(GridCellType cellType, GridCellRange range, C1Style style, C1Thickness internalBorders)
{
base.PrepareCellStyle(cellType, range, style);
var tempFColumn = Grid.Columns["TemperatureF"];
var tempCColumn = Grid.Columns["TemperatureC"];
// セル値に基づいてTempratureF列のセルをスタイル設定します。
if (cellType == GridCellType.Cell && tempFColumn.Index == range.Column)
{
var _value = (int)Grid[range.Row, range.Column];
if (_value > 64 && _value < 95)
{
style.Color = C1Color.Green;
}
else
{
style.Color = C1Color.Red;
}
}
// セル値に基づいてTempratureC列のセルをスタイル設定します。
if (cellType == GridCellType.Cell && tempCColumn.Index == range.Column)
{
var _value = (int)Grid[range.Row, range.Column];
if (_value > 19 && _value < 35)
{
style.Color = C1Color.Green;
}
else
{
style.Color = C1Color.Red;
}
}
// ヘッダーをスタイル設定します。
if (cellType == GridCellType.ColumnHeader)
{
style.BackgroundColor = "#FFC0CB";
style.Color = C1Color.Black;
}
if (cellType == GridCellType.Cell && range.Row % 2 == 0)
{
style.BackgroundColor = "#90EE90";
}
}
}
}