在ListView Windows表单中没有项目时,显示空文本



当我内部没有项目时,我正在尝试在listView中显示一个空文本消息(这是表单初始化的时)。

我尝试搜索使用`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();
        }

您可以处理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);
        }
    }
}

最新更新