【问题标题】:Display empty text when there are no items in ListView Windows forms当 ListView Windows 窗体中没有项目时显示空文本
【发布时间】:2016-12-10 13:45:28
【问题描述】:

当我在列表视图中没有项目时(即初始化表单时),我试图在列表视图中显示一条空文本消息。

我已经尝试搜索不同的方法,其中一种方法是使用 `OnPaint() 事件,但效果不佳...

有人可以帮帮我吗? ` 编辑:这是我尝试过的方法之一:

  protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 20)
            {
                if (this.Items.Count == 0)
                {
                    _b = true;
                    Graphics g = this.CreateGraphics();
                    int w = (this.Width - g.MeasureString(_msg,
                      this.Font).ToSize().Width) / 2;
                    g.DrawString(_msg, this.Font,
                      SystemBrushes.ControlText, w, 30);
                }
                else
                {
                    if (_b)
                    {
                        this.Invalidate();
                        _b = false;
                    }
                }
            }

            if (m.Msg == 4127) this.Invalidate();
        }

【问题讨论】:

  • 您是否忘记检查 null 以及 Items.Count 是否
  • @jdweng 是的,我已经检查过了,由于某种原因它根本不起作用。这就是为什么我正在寻找一种不同的方法来显示空文本
  • 你遇到异常了吗?
  • 不,表单运行无异常,但列表视图仅显示标题列:/
  • 你可以处理0xF消息。

标签: c# winforms listview empty-list


【解决方案1】:

您可以处理WM_PAINT(0xF) 消息并检查Items 集合中是否没有项目,在ListView 的中心绘制一个字符串。例如:

using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;

public class MyListView : ListView
{
    public MyListView()
    {
        EmptyText = "No data available.";
    }
    [DefaultValue("No data available.")]
    public string EmptyText { get; set; }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == 0xF)
        {
            if (this.Items.Count == 0)
                using (var g = Graphics.FromHwnd(this.Handle))
                    TextRenderer.DrawText(g, EmptyText, Font, ClientRectangle, ForeColor);
        }
    }
}

【讨论】:

  • 在表单上显示项目时如何在表单上实现这一点?
  • P.S.我问这个的原因是因为我在表单上的列表视图只是简单地拖动然后在后面的代码中使用,这就是为什么我很确定如何使用这个代码来组合它? :)
  • 这是一个新的MyListView 控件,它派生自ListView。因此,当您将此控件添加到您的项目时,您可以将它的一个实例从工具箱拖放到您的表单中,并像使用任何其他控件一样使用它。
  • 哦!一会儿我会试一试:)
  • 不要忘记构建项目,然后它将在第一个组件选项卡的工具箱中可用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多