【问题标题】:Listview: Align Column Header Separately from Items in Column?Listview:将列标题与列中的项目分开对齐?
【发布时间】:2014-12-13 06:16:25
【问题描述】:

我想像这样对齐我的 Listview 列标题

图例: (C) = 居中对齐,(L) = 左对齐

(L) Column Header 1 | (C) Header 2 | (C) Header 3 | (L) Header 4

Listview 中的所有项目然后左对齐(L)

我在添加/编辑列时知道 .TextAlign 属性,但是,无论对齐到什么,该列中的项目也相同,(即我设置为 (C) 的列标题也将具有这些列中的所有项目都居中对齐,这是我不想要的。)

这可行吗?

【问题讨论】:

  • 你能发布一些你的代码 - 更好地理解你的问题。
  • 真的没有代码可以发布,哈哈。一切都在问题之中;我使用列的.TextAlign 属性来布局列,现在我只希望我添加到列表视图的所有项目都是左对齐的。
  • 几乎没有。 LV Column 不为 HeaderTextAlign 和 ItemTextAlign 提供单独的属性。它不是网格。
  • 到目前为止超过 2500 次观看,获得了“值得注意的问题”徽章,而不是 1 次支持...现在来吧,人们...:P

标签: c# .net vb.net


【解决方案1】:

你可以OwnerDrawColumnHeaders:设置listView1.OwnerDraw = true;

这是一个为三个 Columns 设置单独对齐的示例:

private void listView1_DrawColumnHeader(object sender, 
                                        DrawListViewColumnHeaderEventArgs e)
{
    ColumnHeader ch = listView1.Columns[e.ColumnIndex];
    HorizontalAlignment colHal = ch.TextAlign;
    HorizontalAlignment headHal = colHal;

    // three headers that use a different alignment than the columns :
    if (e.ColumnIndex == 0) headHal = HorizontalAlignment.Center;
    if (e.ColumnIndex == 1) headHal = HorizontalAlignment.Right;
    if (e.ColumnIndex == 2) headHal = HorizontalAlignment.Left;

    SizeF size = e.Graphics.MeasureString(ch.Text, e.Font);

    float x = 
        headHal == HorizontalAlignment.Center ? ( e.Bounds.Width - size.Width ) / 2f :
        headHal == HorizontalAlignment.Right  ? ( e.Bounds.Width - size.Width ) : 0f;

    e.DrawBackground();

    using (SolidBrush brush = new SolidBrush(e.ForeColor) )
           e.Graphics.DrawString(ch.Text, e.Font, brush, 
                                 e.Bounds.X + x, 5f, StringFormat.GenericDefault);
}

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    e.DrawDefault = true;
}

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    e.DrawDefault = true;
}

您可能需要使用5f 垂直偏移量,具体取决于您的字体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多