WPF DataGrid Column Widths and Reordering

I have a DataGrid defined as

<wpftoolkit:DataGrid
        x:Name="AccountsDataGrid"
        AutoGenerateColumns="False"
        ItemsSource="{Binding Path=Accounts}"
        ColumnReordered="DataGrid_ColumnReordered"
        SelectionUnit="FullRow"
        RowHeaderWidth="0"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        >
        <wpftoolkit:DataGrid.Columns>
            <wpftoolkit:DataGridTextColumn Header="Account Id" Binding="{Binding Path=AccountId}" Width="Auto" />
            <wpftoolkit:DataGridTextColumn Header="Account Name" Binding="{Binding Path=AccountName}" Width="*" />
        </wpftoolkit:DataGrid.Columns>
    </wpftoolkit:DataGrid>

which looks great when loading. the first column corresponds to the minimum width required to accommodate both the content and the title. the second column is stretched to fill the rest of the width of the DataGrid (so I don't have a third column of filler). But if I try to reorder the columns, the AccountName column cannot be resized to a width smaller than its width before reordering. So I added a ColumnReordered event handler, believing that I can just reset the width of the column, but it doesn't seem to work. In fact, it reduces the AccountId column to almost zero, and the AccountName column still cannot be reduced less.

private void DataGrid_ColumnReordered(object sender, Microsoft.Windows.Controls.DataGridColumnEventArgs e)
    {
        foreach (DataGridColumn column in AccountsDataGrid.Columns)
        {
            if (column.Equals(AccountsDataGrid.Columns.Last()))
            {
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Star);
            }
            else
            {
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
            }
        }
    }

+3
1

. DisplayIndexes. :

  private void DataGrid_ColumnReordered(object sender, DataGridColumnEventArgs e)
    {
        int lastColumnOrder = AccountsDataGrid.Columns.Count() - 1;
        foreach (DataGridColumn column in AccountsDataGrid.Columns)
        {
            if (column.DisplayIndex == lastColumnOrder)
            {
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Star);
            }
            else
            {
                column.Width = new DataGridLength(1.0, DataGridLengthUnitType.Auto);
            }
        } 
    }
+3

Source: https://habr.com/ru/post/1714577/


All Articles