ListView Final Column Autosize creates scrollbar

前端 未结 8 1182
闹比i
闹比i 2021-01-13 18:23

I am implementing a custom control which derives from ListView.

I would like for the final column to fill the remaining space (Quite a common task), I have gone abou

8条回答
  •  Happy的楠姐
    2021-01-13 18:52

    When a form containing a listview is restored to FormWindowState.Normal from a maximized state, horizontal scroll bar is displayed even though column widths have been correctly adjusted. This happens when the resized column width shrinks but not when it grows. Here's a hack that can correct this without resorting to win32 calls. (magic number [-2] is just a simple shortcut)

            // Member variable.
            private ListView myListView;
    
            // Method to resize last column.
            private void ResizeColumn(int width) {
                  myListView.Columns[myListView.Columns.Count - 1].Width = width;
            }                  
    
            // ListView ClientSizeChanged event handler.
            private void Process_ListViewClientSizeChanged(object sender, EventArgs e)
            {
                  // Get the width to resize the last column.
                  int width = myListView.ClientSize.Width;
                  for (int i = 0; i < myListView.Columns.Count - 1; i++)
                        width -= myListView.Columns[i].Width;
    
                  // Last column width is growing. Use magic number to resize.
                  if (width >= myListView.Columns[myListView.Columns.Count - 1].Width)
                        myListView.Columns[myListView.Columns.Count - 1].Width = -2;
    
                  // Last column width is shrinking. 
                  // Asynchronously invoke a method to resize the last column.
                  else
                        myListView.BeginInvoke
                              ((MethodInvoker)delegate { ResizeColumn(width); });
            }
    

提交回复
热议问题