You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinForm中如何去除ListView列标题最后一列的空白区域?

WinForm ListView深色模式下移除列头末尾空白区域的解决方法

要解决深色模式下ListView最大化后列头末尾空白区域显眼的问题,基于你已经尝试的重绘列头思路,可通过以下两种方式实现:

方法一:重绘时填充空白区域(保留原有列宽)

  1. 确保ListView的OwnerDraw属性设置为true
  2. 完善列头重绘事件的逻辑,在绘制完所有列头后,用列头背景色填充剩余空白区域:
private void ListView_DrawColumnHeader_Dark(object sender, DrawListViewColumnHeaderEventArgs e)
{
    // 绘制默认列头的背景和文本
    e.DrawBackground();
    e.DrawText();

    ListView listView = (ListView)sender;
    // 计算所有列头的总宽度
    int totalColumnWidth = listView.Columns.Cast<ColumnHeader>().Sum(col => col.Width);
    int headerAreaWidth = listView.ClientRectangle.Width;

    // 若列总宽度小于控件宽度,填充空白区域
    if (totalColumnWidth < headerAreaWidth)
    {
        using (SolidBrush bgBrush = new SolidBrush(e.BackColor))
        {
            e.Graphics.FillRectangle(bgBrush, totalColumnWidth, e.Bounds.Top, headerAreaWidth - totalColumnWidth, e.Bounds.Height);
        }
    }
}
  1. 绑定ListView的Resize事件,窗口大小变化时触发重绘:
private void ListView_Resize(object sender, EventArgs e)
{
    ((ListView)sender).Invalidate();
}

方法二:让最后一列自动扩展填充空白(调整列宽)

如果允许调整最后一列的宽度,可在窗口大小变化时动态设置最后一列宽度,直接覆盖空白区域:

private void ListView_Resize(object sender, EventArgs e)
{
    ListView listView = (ListView)sender;
    if (listView.Columns.Count == 0) return;

    // 计算除最后一列外的总宽度
    int totalWidth = 0;
    for (int i = 0; i < listView.Columns.Count - 1; i++)
    {
        totalWidth += listView.Columns[i].Width;
    }

    // 设置最后一列宽度为控件剩余空间
    listView.Columns[listView.Columns.Count - 1].Width = listView.ClientRectangle.Width - totalWidth;
}

内容的提问来源于stack exchange,提问作者noobDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 21:36:19