c# - WPF 为所有 DataGrid 列设置单元格样式
问题描述
这是我的问题。我在一个进行一些物理计算的应用程序上工作,我需要将所有结果作为数据网格输出。这将需要 30 多个唯一列。在旧版本的应用程序中,我们只是使用了 DataGridTextColumn
<DataGridTextColumn Header="Section Type" Binding="{Binding SectionType}"/>
<DataGridTextColumn Header="Liquid Density, kg/m^3" Binding="{Binding LiquidDensity}"/>
...
但问题是我需要对每个单元格应用一些样式,比如使它们不可聚焦、居中等。这是我找到的唯一解决方案。
<DataGrid.Resources>
<Style x:Key="NotFocusable" TargetType="{x:Type DataGridCell}">
<Setter Property="Focusable" Value="False"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Inlet Point" Binding="{Binding InletPoint}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontFamily" Value="Noto Sans"/>
</Style>
</DataGridTextColumn.ElementStyle>
<DataGridTextColumn.CellStyle>
<Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource NotFocusable}"/>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
...
</DataGrid.Columns>
鉴于我需要几十个这样的事实,这对于一列来说是很多代码。我觉得只为一个数据网格使用 500 多行代码是一种糟糕的方法。
是否有可能以某种方式只设置一次样式,然后在一行中声明列,就像在第一个示例中一样,或者至少为此使用更少的代码行?
解决方案
您可以为每个 DataGrid 定义一次 CellStyle,而不是为列定义一次。可以通过声明资源和使用带有 StaticResource 扩展的属性语法来缩短设置 ElementStyle:
<DataGrid.CellStyle>
<Style x:Key="NotFocusable" TargetType="{x:Type DataGridCell}">
<Setter Property="Focusable" Value="False"/>
</Style>
</DataGrid.CellStyle>
<DataGrid.Resources>
<Style x:Key="TextCell" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontFamily" Value="Noto Sans"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Inlet Point" Binding="{Binding InletPoint}" ElementStyle="{StaticResource TextCell}"/>
...
</DataGrid.Columns>
推荐阅读
- azure - 如何在 azure cli 上启用 az 安全评估
- reactjs - App.js react native RBAC登录系统问题
- android - 我们如何在 laravel 中创建 Soap 服务器并使用 laravel wsdl url 调用移动应用程序
- sass - 表格单元格宽度 - 最后一个最长,前一个相等但尽可能窄
- jenkins - 詹金斯工作的自定义指标
- r - R:创建连续的时间线
- java - 获取工具提示文本
- python - 如何在 django rest 框架中设置不需要的序列化器字段?
- javascript - 如何汇总从数据库中检索到的下拉列表中选择的商品的价格
- python - 循环遍历生成列表的生成器