首页 > 解决方案 > C#:Listview LargeIcon 视图:消除行之间的空间

问题描述

我正在为特定目的/应用程序构建一个自定义 ListView 控件,我必须在其中显示画廊。为此,我使用所有者绘制的过程在 ListView 中手动绘制图像。

我在 ListView 中的图像将是 128x128 像素,因此我将一个空白 ImageList 控件(图像尺寸为 128x128)作为图像列表分配给 ListView 以自动定义项目大小。

在此处输入图像描述

到目前为止,这对我来说很好。但我需要消除项目行之间的空间(如示例图像所示)。我的目标是使自定义列表视图看起来像一个图像网格。我不担心项目左右的空间,只需要去掉行之间的空间,使它看起来像一个连续的网格。

任何帮助表示赞赏。谢谢。

标签: c#winformslistviewownerdrawn

解决方案


切换到平铺视图并执行您自己的绘图可以避免行间距问题:

listView1.TileSize = new Size(128, 128);
listView1.View = View.Tile;
listView1.OwnerDraw = true;
listView1.DrawItem += listView1_DrawItem;

和一个简单的绘图程序:

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e) {
  Color textColor = SystemColors.WindowText;
  if (e.Item.Selected) {
    if (listView1.Focused) {
      textColor = SystemColors.HighlightText;
      e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
    } else if (!listView1.HideSelection) {
      textColor = SystemColors.ControlText;
      e.Graphics.FillRectangle(SystemBrushes.Control, e.Bounds);
    }
  } else {
    using (SolidBrush br = new SolidBrush(listView1.BackColor)) {
      e.Graphics.FillRectangle(br, e.Bounds);
    }
  }

  e.Graphics.DrawRectangle(Pens.Red, e.Bounds);
  TextRenderer.DrawText(e.Graphics, e.Item.Text, listView1.Font, e.Bounds,
                        textColor, Color.Empty,
                        TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
}

结果:

在此处输入图像描述


推荐阅读