This page outlines the customization of a DataGrid object. The customization includes modifying row and cell colors dynamically based on predefined conditions.
Before customizing DataGrid colors, the data source must be configured to handle it. However, this example preloads data in the CodeBehind to demonstrate the color customization.
Row Customization
OnCustomizeRow(DataRow row, Dictionary<string, object> attributes)
coloredGridByRow
based on row index parity, applying alternating colors for even and odd indices.private void OnCustomizeRow(DataRow row, Dictionary<string, object> attributes) { // Retrieves the total number of rows in the table. int rowCount = row.Table.Rows.Count; // Retrieves the index of the current row in the table. int idx = row.Table.Rows.IndexOf(row); // Defines default text color as green and background color as black. string textColor = "#000000"; string bgColor = "#FFFFFF"; // Alternates colors for even and odd row indices. if (idx % 2 == 0) { textColor = "#000000"; bgColor = "#DAF3DB"; } // Assigns the foreground and background colors to the row attributes. attributes["Foreground"] = textColor; attributes["Background"] = bgColor; } |
Cell Customization
OnCustomizeCell(string columnName, DataRow row, Dictionary<string, object> attributes)
private void OnCustomizeCell(string columnName, DataRow row, Dictionary<string, object> attributes) { // Logs debug information when the method executes. @Info.Trace($"[DEBUG] || OnCustomizeCell || col: {columnName} || [1] "); // Exits the method if the column is not named "Status". if (!string.Equals(columnName, "Status")) return; // Logs debug information when the column matches "Status". @Info.Trace($"[DEBUG] || OnCustomizeCell || col: {columnName} || [2] "); // Retrieves the value of the "Status" column string status = row["Status"]?.ToString(); if (string.IsNullOrEmpty(status)) return; // Logs debug information about the retrieved value. @Info.Trace($"[DEBUG] || OnCustomizeCell || col: {columnName} || Row[col]: {row[columnName]} || [3] "); // Apply background and text colors based on status value using if-else if (status.Contains("2nd Pass Press")) { attributes["Foreground"] = "#FFFFFF"; attributes["Background"] = "#00B9B6"; } else if (status.Contains("Finished Press")) { attributes["Foreground"] = "#000000"; attributes["Background"] = "#8BE27C"; } else if (status.Contains("Finish Slit")) { attributes["Foreground"] = "#000000"; attributes["Background"] = "#FCFD1A"; } else if (status.Contains("Start Slit")) { attributes["Foreground"] = "#FFFFFF"; attributes["Background"] = "#1929A9"; } else if (status.Contains("Finished Lam")) { attributes["Foreground"] = "#000000"; attributes["Background"] = "#57D845"; } else if (status.Contains("2nd Pass Lam")) { attributes["Foreground"] = "#FFFFFF"; attributes["Background"] = "#1A2B7E"; } } |
→ See DataGrid Control for more information.
In this section: