GridView column width does not update when changing ItemsSource

早过忘川 提交于 2019-12-01 01:30:30
Igal

Use this code after updating ItemsSource:

public void AutoSizeGridViewColumns(ListView listView) 
{ 
    GridView gridView = listView.View as GridView; 
    if (gridView != null)
    { 
        foreach (var column in gridView.Columns)
        {
            if (double.IsNaN(column.Width))
                column.Width = column.ActualWidth; 
            column.Width = double.NaN; 
        } 
    } 
} 

I have created the following class and used across the application whereever required in place of GridView

/// <summary>
/// Represents a view mode that displays data items in columns for a System.Windows.Controls.ListView control with auto sized columns based on the column content     
/// </summary>
public class AutoSizedGridView : GridView
{        
    protected override void PrepareItem(ListViewItem item)
    {
        foreach (GridViewColumn  column in Columns)
        {
            //setting NaN for the column width automatically determines the required width enough to hold the content completely.
            //if column width was set to NaN already, set it ActualWidth temporarily and set to NaN. This raises the property change event and re computes the width.
            if (double.IsNaN(column.Width)) column.Width = column.ActualWidth;
            column.Width = double.NaN;              
        }            
        base.PrepareItem(item);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!