WPF: Change DataGrid cell/row background color dynamically at runtime

前端 未结 1 1807
慢半拍i
慢半拍i 2021-01-16 11:04

I have multiple DataGrids bound to DataTables, which are dynamically created using SQL. Whenever DataTable records change (add, modify, delete), the DataGridCells shall chan

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-16 11:49

    For completeness:

    If you really intend to change the color at runtime, disregarding MVVM you can for instance use DataGrid_LoadingRow, check for it's DataContext (in this case a DataRowView) and go on from there:

    // Changes beeing made to the entire row in this case
    private void DgModules_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        DataGridRow gridRow = e.Row;
        DataRow row = (gridRow.DataContext as DataRowView).Row;
        switch (row.RowState)
        {
            case DataRowState.Added:
                gridRow.Background = new SolidColorBrush(Colors.Green);
                break;
            case DataRowState.Modified:
                gridRow.Background = new SolidColorBrush(Colors.Yellow);
                break;
            case DataRowState.Deleted:
                gridRow.Background = new SolidColorBrush(Colors.Red);
                break;
        }
    }
    

    If you wanna approach this actually using MVVM, go for this solution.

    0 讨论(0)
提交回复
热议问题