.net 如何以编程方式使 ListView 的列自动调整大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/57584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:48:01  来源:igfitidea点击:

How can I make a ListView's columns auto-resize programmatically?

.netwindowsuser-interfacecontrols

提问by Luke

I've found some examples using the Win32 api or simulating the ^+ button combination (ctrl-+) using SendKeys, but at least with the SendKeys method the listview grabs the cursor and sets it to an hourglass until I hit the start button on my keyboard. What is the cleanest way to do this?

我找到了一些使用 Win32 api 或使用 SendKeys模拟 ^+ 按钮组合(ctrl- +)的示例,但至少使用 SendKeys 方法,列表视图会抓取光标并将其设置为沙漏,直到我按下键盘上的开始按钮. 什么是最干净的方法来做到这一点?

回答by Matt Nelson

Looks like a call to myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)will do what you want. I would think, just call it after adding an item.

看起来像一个电话myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)会做你想做的事。我想,只需在添加项目后调用它。

More info here

更多信息在这里

回答by rpetrich

According to MSDN, if you set the column width to -1 then it will autosize to the widest item

根据MSDN,如果您将列宽设置为 -1,那么它将自动调整为最宽的项目

回答by RonB

loop through all columns and set width to -1 after adding content.

添加内容后循环遍历所有列并将宽度设置为 -1。

回答by Chris Raisin

After adding the following routine to your code then call it from any procedure/function. Do not use it in your "Form_Load" procedure though. Only call it after you have added an item to your ListView (or if you are making multiple additions, call it once at the end of all the additions):

将以下例程添加到您的代码后,然后从任何过程/函数调用它。但是不要在“Form_Load”过程中使用它。仅在将项目添加到 ListView 后才调用它(或者如果您要进行多次添加,请在所有添加结束时调用一次):

    Private Sub AutoSizeListViewColumns(oListView As ListView)
        Dim nCol As Integer = 0
        SuspendLayout()
        For nCol = 0 To (oListView.Columns.Count - 1)
            oListView.Columns(nCol).Width = -1  'forces autosizing on column
        Next
        oListView.Refresh()
        ResumeLayout()
    End Sub