Search code examples
.netwpfdatagridwpfdatagridresize

WPF DataGrid: resizing columns


I have a System.Windows.Controls.DataGrid with property CanUserResizeColumns assigned to True. Now I can adjust the width of the columns by using the mouse left button click between 2 column headers.

But I also want to be able to change the width of the columns in any row of the dataGrid, not only in the column headers. Is it possible?


Solution

  • In your dataGrid you can use a DataGridTemplate column alogn with a GridSplitter to achieve this..

     <toolkit:DataGridTemplateColumn Header="Text" >
         <toolkit:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
               <Grid>
                  <Grid.ColumnDefinitions>
                     <ColumnDefinition Width="*"/>
                     <ColumnDefinition  Width="Auto"/>
                  </Grid.ColumnDefinitions>
                  <TextBlock Text="{Binding Text}"/>
                  <GridSplitter Grid.Column="1" Width="3"
                                DragIncrement="1"
                                DragDelta="GridSplitter_DragDelta"
                                Tag="{Binding BindsDirectlyToSource=True,
                                        RelativeSource={RelativeSource
                                          AncestorType={x:Type toolkit:DataGridCell}}}"/>
               </Grid>
            </DataTemplate>
         </toolkit:DataGridTemplateColumn.CellTemplate>
     </toolkit:DataGridTemplateColumn>
    

    Then in your code behind... do this...

        private void GridSplitter_DragDelta(
             object sender,
             System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            var gridSplitter = sender as GridSplitter;
    
            if (gridSplitter != null)
            {
                ((DataGridCell) gridSplitter.Tag).Column.Width
                    = ((DataGridCell) gridSplitter.Tag).Column.ActualWidth +
                      e.HorizontalChange;
            }
        }
    

    This way a GridSplitter at individual cell level can resize its entire column.

    If you are using MVVM then the above event handler should be put in an Attached Behavior