【问题标题】:C#: Listview LargeIcon view: Eliminating space between rowsC#:Listview LargeIcon 视图:消除行之间的空间
【发布时间】:2018-07-11 00:58:43
【问题描述】:

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

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

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

感谢任何帮助。谢谢。

【问题讨论】:

  • 如果切换到 OwnerDraw(绘制矩形内容的地方),您可以将视图切换到 Tile。或者试试.NET ListView row padding
  • 您实际上可以在 e.Bounds 矩形之外进行绘制。但是使用 Tile 可能是最简单和最好的解决方案,尽管它仍然会有小的差距。
  • @LarsTech Tile 方法确实解决了行之间的空间问题,但现在我无法更改项目大小。您提到的帖子仅适用于 LargeIcon 视图模式。 --编辑:我刚刚注意到 TileSize 属性。谢谢。
  • @TaW 是的,我尝试在 Bounds 维度之外进行绘图,但问题出现在最后一行;绘图超出了 ListView 的范围。

标签: c# winforms listview ownerdrawn


【解决方案1】:

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

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);
}

结果:

【讨论】: