Syncfusion SfDataGrid でセルの背景色を変える方法です。
※ この記事の投稿時点の SfDataGrid のバージョンは v15.2.0.46 です。
セルの背景色の変更は GridCell
クラスを継承したクラスを GridColumn
クラス UserCellType
プロパティに指定します。背景色以外も自由にカスタマイズできます。
ちなみに、行全体の背景色を変えるには DataGridStyle
クラスが使えます(Styles 参照)。
次のようにユーザー定義のセルを作ります。
public class ColoredCell : GridCell
{
private readonly TextView _textView;
private readonly View _view;
public ColoredCell(Context context) : base(context)
{
_view = new View(context);
_textView = new TextView(context)
{
Gravity = GravityFlags.Center
};
_textView.SetTextColor(Color.Black);
AddView(_view);
AddView(_textView);
CanRenderUnLoad = false;
}
protected override void UnLoad()
{
(Parent as VirtualizingCellsControl)?.RemoveView(this);
}
protected override void OnLayout(bool change, int l, int t, int r, int b)
{
_view.Layout(1, 1, Width - 1, Height - 1);
_textView.Layout(1, (int)(10 * Resources.DisplayMetrics.Density), Width, Height);
}
protected override void OnDraw(Canvas canvas)
{
base.OnDraw(canvas);
var valueText = DataColumn.CellValue.ToString();
_textView.Text = valueText;
if (bool.TryParse(valueText, out var result) && result)
{
_view.SetBackgroundColor(Color.Orange);
}
}
}
GridColumn.UserCellType
に設定します。
var col = new GridTextColumn {
};
col.UserCellType = typeof(ColoredCell);
_dataGrid.Columns.Add(col);