Tuesday, January 4, 2011

How to resize the columns of WPF List View according to the width of the content

You may need to re size the width of a WPF list view to fit to the width of the cell with longest item in the column. Here is the sample code. Please note here I am not showing you the XAML example. But it is same the you can call "ResizeListViewColumnsToContent" event handle on List view load as below with XAML also.


private static void ResizeListViewColumnsToContent(object sender, RoutedEventArgs e)
    {
      var listView = (ListView)sender;
      var 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;
        }
      }
    }




Then you can use this method anywhere you need to resize the list view columns according to the content.
For an example as follows as list view Loaded event.

ListView listView = new ListView();
listView .Loaded += ResizeListViewColumnsToContent;

Or else like follows.

ListView listView = new ListView();
ResizeListViewColumnsToContent(listView, null)

Please note that the ListView I am talking here is System.Windows.Controls.ListView

0 comments:

Post a Comment