I want to write style for WPF DataGrid Column Header . My grid as follows
`<DataGrid >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<Label Content="{DynamicResource colName}"></Label>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>`
I want to bind label content using DynamicResource. This code is working properly. I want write a style to apply this binding method to grid column. I wrilte a style as follows.
`<Style x:Key="ColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridColumnHeader">
<Label Content="{ TemplateBinding Content}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>`
I apply this style to grid as follows.
<DataGrid >
<DataGrid.Columns>
<DataGridTextColumn HeaderStyle="{StaticResource ColumnHeaderStyle}" Header="{ DynamicResource colName}" />
</DataGrid.Columns>
</DataGrid>
After using style header not binding. How can I solve this problem?
Thanks!
We can try as follows
<Style x:Key="ColumnHeaderStyle" TargetType="{x:Type dg:DataGridColumnHeader}">
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Background" Value="Black" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="dg:DataGridColumnHeader">
<dg:DataGridHeaderBorder
x:Name="headerBorder"
Background="Red">
<Border BorderThickness="1"
CornerRadius="2"
Background="Black"
BorderBrush="Green">
<Grid>
<TextBlock Text="{TemplateBinding Content}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap"/>
</Grid>
</Border>
</dg:DataGridHeaderBorder>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<dg:DataGrid Grid.Row="1" Grid.RowSpan="1"
Name="UserName"
HorizontalAlignment="Left"
AutoGenerateColumns="True"
Width="800"
Background="Yellow"
ColumnHeaderHeight="20"
ColumnHeaderStyle="{DynamicResource ColumnHeaderStyle}"
RowStyle="{StaticResource RowStyle}"
CanUserAddRows="False"
CanUserDeleteRows="False"
/>
Define Header
as a StaticResource
not Dynamic. This will fix your issue
<DataGridTextColumn HeaderStyle="{StaticResource ColumnHeaderStyle}" Header="{ StaticResource colName}" />
Or you can update your controlTemplate's label to have DynamicResource
and no need of giving Header
then.
<ControlTemplate TargetType="DataGridColumnHeader">
<Label Content="{ DynamicResource colName}"/>
</ControlTemplate>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.