简体   繁体   English

FontSize更改后自动WPF DataGrid

[英]WPF DataGrid auto after FontSize changed

I have a DataGrid with some columns' width set to "auto". 我有一个数据网格,其中某些列的宽度设置为“自动”。 Now I'm changing the FontSize. 现在,我要更改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. 当我增大FontSize时,列会变宽,但是当我减小FontSize时,列宽不会根据FontSize缩小。

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

Is there a way to force the DataGrid to recalculate all "auto" and "*" values? 有没有一种方法可以强制DataGrid重新计算所有“自动”和“ *”值?

Easiest way is set ItemsSource to null , and then re-assign it. 最简单的方法是将ItemsSource设置为null ,然后重新分配它。 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();
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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