0
votes

I have a DataGrid with some columns' width set to "auto". Now I'm changing the FontSize. When I make the FontSize larger, columns get wider, but when I make the FontSize smaller, the column width doesn't shrink according to the FontSize.

<DataGridTextColumn ....
                    Width="auto" 
                    ....

Is there a way to force the DataGrid to recalculate all "auto" and "*" values?

2
Where have you changed the code of FontSize? Give a full code of your Data Grid.Mr.B
I just set: dataGrid.FontSize = something;be_mi

2 Answers

1
votes

Reseting of column's width works:

 foreach (var dataGridColumn in dg.Columns)
            {
                dataGridColumn.Width = new DataGridLength(20);
                dataGridColumn.Width = new DataGridLength();
            }
1
votes

Easiest way is set ItemsSource to null, and then re-assign it. Eg;

// This method works for AutoGenerateColumns = true
   Dgrd.FontSize = 8;
   Dgrd.ItemsSource = null;
   Dgrd.ItemsSource = ...;

And general method would be to store old width values of columns, and then using them to restore. Eg;

    Dictionary<DataGridColumn, double> columns = new Dictionary<DataGridColumn, double>();

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        Dgrd.FontSize = 20;

        columns.Clear();
        foreach (DataGridColumn col in Dgrd.Columns)
        {
            columns.Add(col, col.ActualWidth);
        }
    }

    private void Button_Click_2(object sender, RoutedEventArgs e)
    {
        Dgrd.FontSize = 8;            

        foreach (DataGridColumn col in Dgrd.Columns)
        {
            col.Width = columns[col];
        }
    }