C#Listview使列大小等于listview宽度的一半

时间:2014-03-18 16:31:00

标签: c# listview user-interface

我有一个listview对象,我希望有2列。我希望两列在列表视图的宽度上伸展,并使每个列的列标题都居中。如果我将列的大小设置为-2(自动大小),我会得到以下结果(代码后跟屏幕截图):

        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", -2, System.Windows.Forms.HorizontalAlignment.Center);
        this.recipList.Columns.Add("Number of Reports", -2, System.Windows.Forms.HorizontalAlignment.Center);

enter image description here

如果我在这个窗口中手动拖动列来模仿我想要的东西,我就明白了。这里唯一的问题是,即使将Recipient设置为HorizontalAlignment.Center,在将其拖动到我想要的位置后,它仍然会左对齐:

enter image description here

此时我想方法是让两列都跨越listview框的整个宽度,并且每列占据一半,我只需要将每列的大小设置为1/2整个列表视图的宽度。所以我这样做:

        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。这会产生以下结果:

enter image description here

正如您所看到的,它几乎与2个问题有关。

  1. Number of Reports列横跨列表视图框并创建滚动条。我不想要这个。
  2. 即使收件人设置为HorizontalAlignment.Center,收件人仍然是左对齐的。
  3. 有没有更好的方法来解决这两个问题?

2 个答案:

答案 0 :(得分:0)

首先,您可以为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);

它在MSDN Page上解释。

答案 1 :(得分:0)

宽度是ListView的外部宽度,包括边框像素。将它们计算为您的bordertyle并使您的列更小一些。或者如果你想这样做正确使用ClientSize属性See here

ListView中的第一列按设计左对齐 afaik ;所以要模拟一个居中的标题你可以用左边的空格填充它。要以精确的方式执行此操作,您必须使用给定的Font测量文本长度。见here。或计算字母,并以较少的presision感到高兴。或者,我想,你可以使用黑客并添加一个虚拟的第一列..