Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 440
leinad13 Avatar asked Dec 07 '11 11:12

leinad13


1 Answers

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>
like image 71
SOReader Avatar answered Sep 28 '22 02:09

SOReader