WPF globally styling a TextBlock inside a DataGrid

前端 未结 2 496
悲&欢浪女
悲&欢浪女 2021-02-07 10:39

I am encountering a very weird issue. I am trying to apply global styling to several controls within a DataGrid. Most of them work exactly how I would expect them t

相关标签:
2条回答
  • 2021-02-07 10:48

    So with a bit more digging and a little luck, I discovered that WPF does not apply implicit styles inside templates unless the TargetType derives from Control. Since TextBlock doesn't derive from Control, its style is not applied. So you either have to manually apply the style to every non-Control or define the implicit style inside the template.

    The following MSDN blog post explains it in pretty good detail.

    https://docs.microsoft.com/en-us/archive/blogs/wpfsdk/implicit-styles-templates-controls-and-frameworkelements

    0 讨论(0)
  • 2021-02-07 10:49

    Unfortunately, like BrianP said, WPF does not work that way. But, it is possible to set the TextElement properties of the cell style as follows:

    <DataGrid ItemsSource="{Binding Data}" AutoGenerateColumns="False" DockPanel.Dock="Top">
        <DataGrid.CellStyle>
            <Style TargetType="DataGridCell">
                <Setter Property="TextElement.Foreground" Value="Green" />
            </Style>
        </DataGrid.CellStyle>
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Test">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="not globably applied" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>
    
    0 讨论(0)
提交回复
热议问题