How to update the widths of ListViewColumns during runtime?

When I was working on the SyncCopy, I was troubled by the fact that listviewcolumn does not resize its width when new items are added to the listview. You can manually adjust the width of the columns by double click on the border line of each column, or just drag the column to the desired length.

To resize columns programmatically, you can do the following (assuming your listview/gridview is called gridView):

   1: // For each column...
   2:     foreach (var column in gridView.Columns)
   3:     {
   4:         // If this is an "auto width" column...
   5:         if (double.IsNaN(column.Width))
   6:         {
   7:             // Set its Width back to NaN to auto-size again
   8:             column.Width = 0;
   9:             column.Width = double.NaN;
  10:         }
  11:     }

However, when I was trying to refractor/rewrite SyncCopy to use MVVM pattern, this way of doing resizing columns is kind of violating the guideline of MVVM design pattern. I know I can use attached properties in WPF and write a custom property that automatically resize the columns when needed, but I got stuck on when to and what event to hook into in order to execute the code above for programmatically resizing the listview on runtime.

Fortunately I came across  this excellent blog post in Delay’s Blog :

Sometimes all it takes is a little encouragement [How to: Automatically update the widths of ListView columns]

Advertisements
This entry was posted in WPF. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s