Adjust ListView columns to fit with WinForms

后端 未结 5 1644
不知归路
不知归路 2021-02-07 21:50

I have face resize problem of listview columns. If you anchor/docking the listview to normal winform than the listview anchor or docking works well. I mean lis

5条回答
  •  一向
    一向 (楼主)
    2021-02-07 22:35

    Here's my solution;

    Instead of resize event I prefer resizeEnd of form, so that the code will run only once when the resize is complete.

    private void Form1_ResizeEnd(object sender, EventArgs e)
    {
        this.ResizeColumnHeaders();
    }
    

    The ResizeColumnHeaders function sets all columns except the last one to fit against column-content. The last column will be using the magic-value hinted by LexRema.

    private void ResizeColumnHeaders()
    {
        for (int i = 0; i < this.listView.Columns.Count - 1;i++ ) this.listView.AutoResizeColumn(i, ColumnHeaderAutoResizeStyle.ColumnContent);           
        this.listView.Columns[this.listView.Columns.Count - 1].Width = -2;
    }
    

    Also don't forget to call ResizeColumnHeaders() after you load your initial data;

    private void Form1_Load(object sender, EventArgs e)
    {            
        this.LoadEntries();
        this.ResizeColumnHeaders();
    }
    

    One more thing is to prevent flickering while columns-resizes, you need to double-buffer the listview.

    public Form1()
    {
        InitializeComponent();            
        this.listView.DoubleBuffer();            
    }
    

    DoubleBuffer() is actually an extension for easy use.

    public static class ControlExtensions
    {
        public static void DoubleBuffer(this Control control) 
        {
            // http://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form/77233#77233
            // Taxes: Remote Desktop Connection and painting: http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx
    
            if (System.Windows.Forms.SystemInformation.TerminalServerSession) return;
            System.Reflection.PropertyInfo dbProp = typeof(System.Windows.Forms.Control).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            dbProp.SetValue(control, true, null);
        }
    }
    

提交回复
热议问题