leinad13
leinad13

Reputation: 444

WPF DataGrid Column Header Resize with Custom Style

I have a WPF DataGrid (.NET 4) with custom template columns and header styles and would like to be able to adjust the size of the columns :

<DataGridTemplateColumn.HeaderStyle>
    <Style TargetType="DataGridColumnHeader">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="DataGridColumnHeader">
                    <StackPanel Orientation="Horizontal">
                        <Image Source="Images\monitor.png" Width="16" Height="16"/>
                        <TextBlock Text="Hostname" TextWrapping="Wrap" Padding="3"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</DataGridTemplateColumn.HeaderStyle>

Columns can still be sorted and re-arranged but not resized - the gripper does not show. I have seen this answer and looked at the Thumb control, however this seems like massive overkill to reproduce functionality already provided. The MSDN blog post references a StaticResource - RowHeaderGripperStyle which they don't provide!

Upvotes: 12

Views: 10814

Answers (1)

SOReader
SOReader

Reputation: 6017

I always do it this way and it works pretty fine:

<Style TargetType="DataGridColumnHeader">
    <!-- here goes some setters -->

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DataGridColumnHeader">
                <Grid Margin="{TemplateBinding Padding}">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>

                    <!-- some stuff, like border etc. -->

                    <ContentPresenter />

                    <Thumb x:Name="PART_RightHeaderGripper" Grid.Column="1"
                        HorizontalAlignment="Right"
                        Width="2" BorderThickness="1"
                        BorderBrush="{Binding VerticalGridLinesBrush, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"
                        Cursor="SizeWE"/>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Upvotes: 22

Related Questions