ConditionRacer
ConditionRacer

Reputation: 4498

Binding and Styling a DataGridColumnHeader

I have a DataGridColumn like this:

<DataGridTextColumn
    Binding="{Binding
        Path=Name,
        UpdateSourceTrigger=PropertyChanged}"
    HeaderStyle="{StaticResource HeaderWrapped}">

    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock
                Text="{Binding
                    Path=DataContext.Name,
                    RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

The HeaderWrapped style is in a ResourceDictionary that is imported in the control. It looks like this:

<Style x:Key="HeaderWrapped" TargetType="DataGridColumnHeader">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{TemplateBinding Content}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

When I run the app, the header Text is bound properly, but the TextWrapping is not set. I'm guessing that the DataGridTextColumn.HeaderTemplate overwrites the template from my ResourceDictionary. Is there a way that I can keep the styling for the headers in a ResourceDictionary but still bind the Text property of the header?

Upvotes: 0

Views: 544

Answers (1)

Bizhan
Bizhan

Reputation: 17145

What you're trying to do is basically setting a Style for the Header at first, and then tell it to forget about it and use a brand new template for the header. you can't set both DataGridTextColumn.HeaderStyle.ContentTemplate and DataGridTextColumn.HeaderTemplate

However I can think of one workarounds to this problem:

<DataGridTextColumn
    Binding="{Binding
        Path=Name,
        UpdateSourceTrigger=PropertyChanged}"
    Tag="{Binding 
         Path=DataContext.Name,
         RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
    HeaderStyle="{StaticResource HeaderWrapped}">
</DataGridTextColumn>

<Style x:Key="HeaderWrapped" TargetType="DataGridColumnHeader">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock TextWrapping="Wrap" Text="{TemplateBinding Tag}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Upvotes: 1

Related Questions