【问题标题】:WPF Set cell style for ALL DataGrid columnsWPF 为所有 DataGrid 列设置单元格样式
【发布时间】:2021-09-10 19:28:18
【问题描述】:

这是我的问题。我在一个进行一些物理计算的应用程序上工作,我需要将所有结果作为数据网格输出。这将需要 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# wpf datagrid


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-04-28
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2018-09-23
      • 2020-03-27
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多