Home > OS >  WPF Set cell style for ALL DataGrid columns
WPF Set cell style for ALL DataGrid columns

Time:09-16

Here's my problem. I work on an app that does some physics calculations, and I need to output all of the results as a datagrid. That would require more than 30 unique columns. In the old version of the app we just used DataGridTextColumn for that

<DataGridTextColumn Header="Section Type" Binding="{Binding SectionType}"/>
<DataGridTextColumn Header="Liquid Density, kg/m^3" Binding="{Binding LiquidDensity}"/>
...

But the problem is that I need to apply some styles to every cell, like make them non-focusable, centered etc. Here is the only solution I found.

<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>

And that's a lot of code for just one column, given the fact that I need a few dozens of these. I feel like using 500 lines of code just for one datagrid is a terrible way to do it.

Is it possible to somehow set the styles only once and then declare columns in one line, like in the first example, or at least use less lines of code for that?

CodePudding user response:

you can define CellStyle once per DataGrid instead of doing it for columns. Setting ElementStyle can be shortened by declaring a resource and using attribute syntax with StaticResource extension:

<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>
  • Related