C#Listview使列大小等于Listview宽度的一半
我有一个listview对象,我想有两列。我希望这两列在listview的整个宽度上延伸,并使两个列标题都位于每列的中心。如果我将列的大小设置为-2(自动大小),我会得到以下结果(代码后面是屏幕截图): 如果我在这个窗口中手动拖动列来模拟我想要的,我会得到这个。这里唯一的问题是,即使将“收件人”设置为“水平对齐”。在我将其拖动到所需位置后,“居中对齐”仍会保持左对齐: 此时,我认为要使两列跨越listview框的整个宽度,并使每列占据其中的一半,我只需将每列的大小设置为整个listview宽度的1/2。所以我这样做:C#Listview使列大小等于Listview宽度的一半,c#,listview,user-interface,C#,Listview,User Interface,我有一个listview对象,我想有两列。我希望这两列在listview的整个宽度上延伸,并使两个列标题都位于每列的中心。如果我将列的大小设置为-2(自动大小),我会得到以下结果(代码后面是屏幕截图): 如果我在这个窗口中手动拖动列来模拟我想要的,我会得到这个。这里唯一的问题是,即使将“收件人”设置为“水平对齐”。在我将其拖动到所需位置后,“居中对齐”仍会保持左对齐: 此时,我认为要使两列跨越listview框的整个宽度,并使每列占据其中的一半,我只需将每列的大小设置为整个listview宽
this.recipList.Location = new System.Drawing.Point(16, 32);
this.recipList.Name = "recipList";
this.recipList.Size = new System.Drawing.Size(376, 296);
this.recipList.TabIndex = 1;
this.recipList.UseCompatibleStateImageBehavior = false;
this.recipList.View = System.Windows.Forms.View.Details;
this.recipList.Columns.Add("Recipient", 188, System.Windows.Forms.HorizontalAlignment.Center);
this.recipList.Columns.Add("Number of Reports", 188, System.Windows.Forms.HorizontalAlignment.Center);
因为188是376的1/2。这将产生以下结果:
如您所见,它几乎解决了两个问题
Number of Reports
列跨越listview框并创建一个滚动条。我不要这个水平对齐。居中对齐,收件人仍保持左对齐
有更好的方法解决这两个问题吗?首先,您可以为ListView创建标题:
ColumnHeader headerFirst;
ColumnHeader headerSecond;
headerFirst = new ColumnHeader();
headerSecond = new ColumnHeader();
// Set the text, alignment and width for each column header.
headerFirst.Text = "Recipient";
headerFirst.TextAlign = HorizontalAlignment.Left;
headerFirst.Width = 188;
headerSecond.TextAlign = HorizontalAlignment.Left;
headerSecond.Text = "Number of Reports";
headerSecond.Width = 188;
// Add the headers to the ListView control.
ListView1.Columns.Add(headerFirst);
ListView1.Columns.Add(headerSecond);
该宽度是ListView的外部宽度,包括边框像素。根据您的边框样式计算它们,并将列缩小一点。或者,如果您想正确使用ClientSize属性 ListView中的第一列由design afaik左对齐;因此,要模拟居中的标题,可以在其左侧填充空格。要以精确的方式执行此操作,您必须使用给定的字体测量文本长度。看见或者数一数这些字母,以更少的预见性为乐。或者,我想,你可以用一个黑客程序,在第一列中添加一个虚拟列
ColumnHeader headerFirst;
ColumnHeader headerSecond;
headerFirst = new ColumnHeader();
headerSecond = new ColumnHeader();
// Set the text, alignment and width for each column header.
headerFirst.Text = "Recipient";
headerFirst.TextAlign = HorizontalAlignment.Left;
headerFirst.Width = 188;
headerSecond.TextAlign = HorizontalAlignment.Left;
headerSecond.Text = "Number of Reports";
headerSecond.Width = 188;
// Add the headers to the ListView control.
ListView1.Columns.Add(headerFirst);
ListView1.Columns.Add(headerSecond);