11

我的程序:只有一个文本框。我正在使用 C# 语言编写代码。

我的目标:在文本框中显示文本/水印:“请输入您的姓名”。因此,当用户单击文本框时,默认文本/水印会被清除/删除,以便用户可以在文本框中输入他的名字。

我的问题:我尝试了各种在线可用的代码,但它们似乎都不适合我。所以,我想我应该在这里要求一个简单的代码。我在网上找到了一个代码,但这似乎不起作用:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SetWatermark("Enter a text here...");
        }

        private void SetWatermark(string watermark)
        {
            textBox1.Watermark = watermark;
        }
    }
}

错误:

错误 1“System.Windows.Forms.TextBox”不包含“Watermark”的定义,并且找不到接受“System.Windows.Forms.TextBox”类型的第一个参数的扩展方法“Watermark”(您是否缺少使用指令还是程序集引用?)

请,如果您对我的目标有任何其他建议,我将不胜感激。我在网上厌倦了很多例子,但都令人困惑/不起作用。提前感谢您的帮助。:)

4

1 回答 1

36

刚试过这个。它似乎在新的 Windows 窗体项目中运行良好。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        textBox1.ForeColor = SystemColors.GrayText;
        textBox1.Text = "Please Enter Your Name";
        this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);
        this.textBox1.Enter += new System.EventHandler(this.textBox1_Enter);
    }

    private void textBox1_Leave(object sender, EventArgs e)
    {
        if (textBox1.Text.Length == 0)
        {
            textBox1.Text = "Please Enter Your Name";
            textBox1.ForeColor = SystemColors.GrayText;
        }
    }

    private void textBox1_Enter(object sender, EventArgs e)
    {
        if (textBox1.Text == "Please Enter Your Name")
        {
            textBox1.Text = "";
            textBox1.ForeColor = SystemColors.WindowText;
        }
    }
}
于 2013-08-28T20:13:54.393 回答