定义表格样式

定义表格样式
开发工具与关键技术:Visual Studio 2015、WPF
作者:HYJ
撰写时间: 2019年6月15日

新建一个公共类来封装这个表格样式,然后再编写,代码如下:

/// <summary>
/// 定义表格样式
/// </summary>
/// <paramname="dg"></param>
public static voidSetDgStyle(DataGrid dg)
{
//定义样式
Style styleCenter = newStyle(typeof(TextBlock));
//水平对齐方式:居中
Setter setHCenter = newSetter(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center);
//垂直对齐方式:居中
Setter setVCenter = newSetter(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);
//水平对齐方式,垂直对齐方式添加到样式里面
styleCenter.Setters.Add(setHCenter);
styleCenter.Setters.Add(setVCenter);
//设置单元格样式
foreach (DataGridColumnc in dg.Columns)
{
DataGridTextColumntc = c as DataGridTextColumn;
if (tc != null)
{
//应用定义的样式styleCenter
tc.ElementStyle= styleCenter;
}
}
//定义样式
Style columnHeaderstyle= new Style(typeof(DataGridColumnHeader));
//设置水平对齐方式:居中
Setter setRight = newSetter(DataGridColumnHeader.HorizontalContentAlignmentProperty,HorizontalAlignment.Center);
//设置水平对齐方式:居中添加到样式里面
columnHeaderstyle.Setters.Add(setRight);
//应用定义样式columnHeaderstyle
dg.ColumnHeaderStyle =columnHeaderstyle;
//设置表格的行高25
dg.RowHeight = 25;
//设置表格字体大小13.5
dg.FontSize = 13.5;
}

写完之后就可以在需要的后台代码中调用了,实现代码为

//调用封装好的公共类里面的样式
PublicStaticMothd.SetDgStyle(dgCheLiangdyap);

解释:意思是依次按照公共类的名称和样式的名称以及表格的名称调用即可

猜你喜欢

转载自blog.csdn.net/weixin_44547949/article/details/92069708
今日推荐