首页 > 解决方案 > 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 多行代码是一种糟糕的方法。

是否有可能以某种方式只设置一次样式,然后在一行中声明列,就像在第一个示例中一样,或者至少为此使用更少的代码行?

标签: c#wpfdatagrid

解决方案


您可以为每个 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>

推荐阅读