You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过C#自定义WinUI3中CommunityToolkit的DataGrid样式

用C#修改CommunityToolkit.Controls DataGrid的样式属性

针对你通过C#创建的DataGrid,以下是修改行高、边框颜色、字体粗细及字号的具体实现方式:

1. 修改行高

直接设置DataGrid的RowHeight属性即可统一指定所有行的高度:

// 设置行高为30像素
table.RowHeight = 30;

2. 修改边框颜色

通过BorderBrush设置整个DataGrid的边框颜色,配合BorderThickness调整边框粗细;如果需要修改网格线颜色,可设置GridLinesBrush:

// 设置DataGrid边框颜色为深蓝色,边框粗细2像素
table.BorderBrush = new SolidColorBrush(Colors.DarkBlue);
table.BorderThickness = new Thickness(2);

// 设置网格线颜色为灰色(可选,根据需求调整)
table.GridLinesBrush = new SolidColorBrush(Colors.Gray);

3. 修改字体粗细与字号

需要为单元格创建Style,指定字体相关属性,再赋值给DataGrid的CellStyle:

// 创建DataGridCell的样式
Style cellStyle = new Style(typeof(DataGridCell));
// 设置字体粗细为加粗
cellStyle.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold));
// 设置字号为14号
cellStyle.Setters.Add(new Setter(TextBlock.FontSizeProperty, 14));

// 将样式应用到DataGrid的所有单元格
table.CellStyle = cellStyle;

完整修改后的代码示例

DataGrid table = new DataGrid();
table.ColumnWidth = DataGridLength.SizeToCells;
table.AutoGenerateColumns = true;
table.ItemsSource = doubleColumnTable;
table.GridLinesVisibility = DataGridGridLinesVisibility.All;
table.HeadersVisibility = DataGridHeadersVisibility.None;

// 新增样式修改代码
table.RowHeight = 30;
table.BorderBrush = new SolidColorBrush(Colors.DarkBlue);
table.BorderThickness = new Thickness(2);
table.GridLinesBrush = new SolidColorBrush(Colors.Gray);

Style cellStyle = new Style(typeof(DataGridCell));
cellStyle.Setters.Add(new Setter(TextBlock.FontWeightProperty, FontWeights.Bold));
cellStyle.Setters.Add(new Setter(TextBlock.FontSizeProperty, 14));
table.CellStyle = cellStyle;

内容的提问来源于stack exchange,提问作者Biryukov Georgy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 07:42:18