如何使用 C# 对齐 ListView 中单个子项的文本?
对于这个看似简单的主题,我无法在任何地方找到答案:是否可以在 WinForms ListView 控件中对齐单个子项的文本?
如果可以,如何对齐?
我希望同一列中的文本以不同方式对齐。
I wasn't able to find an answer anywhere about this seemingly simple topic: is it possible to align text of a single subitem in a WinForms ListView control?
If so, how?
I would like to have text in the same column aligned differently.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
示例:
将列的“1”对齐设置为右
example :
will set Column's "1" alignment to right
注意:由于底层原生 ListView 控件(位于 comctl32.dll 中)的限制,第一列无法对齐。 它将始终左对齐。
第二个限制是当您自定义绘制(自定义绘制子项)时:当您启用列重新排序时,第一列的文本不会正确重新排序。 我通过不允许对第一列重新排序解决了这个限制(不会称之为错误,因为列表视图支持许多列表样式,并且列表视图的内部数据结构是一棵树),这在大多数情况下没有问题,因为您将为第一列使用某种键,例如数字或类似的键。
Note: Due to a limitation of the underlying native ListView control (living in comctl32.dll), the first column cannot be aligned. It will be always aligned left.
The second limitation is when you custom draw (custom draw subitems): when you enable column reordering, the text of the first column is NOT reordered correctly. I solved this limitation (would not call it a bug, because the listview supports many list styles and the internal data structure of a list view is a tree like one) by not allowing to reorder the first column, which in most cases is no problem, because you'll use some sort of key for the first column like number or something similar.
“ColumnHeader”类具有“TextAlign”属性,该属性将更改列中所有子项的对齐方式。 如果您需要更奇特的东西,您可以随时使用“DrawSubItem”事件并使其所有者绘制。
The "ColumnHeader" class has a "TextAlign" property that will change the alignment for all subitems in the column. If you need something more fancy you could always use the "DrawSubItem" event and make it owner drawn.
为了将来参考,我是这样解决的:
有必要处理 DrawColumnHeader,否则不会绘制任何文本或列分隔符。
For future reference, here's how I solved it:
It was necessary to handle the DrawColumnHeader, otherwise no text or column separators would be drawn.
将ListView控件放在窗体上并将其命名为“listV1”并添加和编辑4列。 同时定义一个索引。
然后,格式化列“0”,不带标题且宽度=0。 这样第 0 列将不可见。 然后您可以根据需要设置其他列的格式(左、中、右),这些列都是可见的。
Put the ListView control on form and name it "listV1" and add and edit 4 columns. Also define one Index.
Then, format column "0" without the header and with Width=0. That way column 0 will be invisible. Then you can format other columns as you wish (left, center,right) which are all visible.
基于@Fueled 的答案,以下是我使用列标题对齐方式所做的操作:
Building on the answer by @Fueled, here's what I did to use the column header alignment: