简体   繁体   中英

WPF DataGrid auto after FontSize changed

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?

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];
        }
    }

Reseting of column's width works:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM