自定义文本框控件
你只需要处理三个TextBox的事件,在设计设置文本框为“用户名”,并使其字体斜体然后设置文本框背景色以浅黄色的文本,其余部分由事件处理程序处理...
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
ChangeTextBoxtoWatermark();
}
private void textBox1_MouseEnter(object sender, EventArgs e)
{
if (textBox1.Text == "username")
{
textBox1.Text = "";
textBox1.Font = new Font(this.Font, FontStyle.Regular);
textBox1.BackColor = Color.White;
}
}
private void textBox1_MouseLeave(object sender, EventArgs e)
{
if (textBox1.Text == "")
ChangeTextBoxtoWatermark();
}
private void ChangeTextBoxtoWatermark()
{
textBox1.Font = new Font(this.Font, FontStyle.Italic);
textBox1.BackColor = Color.LightYellow;
textBox1.Text = "username";
}
我检查了它,它工作得很好:)
您可以折叠代码,如TextBoxToOriginal() – 2012-02-12 10:59:34
这通常被称为“线索”。
- There is a good answer on SO。
- 另外,如果您使用的是DevExpress WinForms,我写了a small class to enhance their
TextEdit
control。
其实。更好的解决方案是使用文本框的Paint事件来绘制字符串。
下面的代码:
class CueTextBox : TextBox
{
public event EventHandler CueTextChanged;
private string _cueText;
public string CueText
{
get { return _cueText; }
set
{
value = value ?? string.Empty;
if (value != _cueText)
{
_cueText = value;
OnCueTextChanged(EventArgs.Empty);
}
}
}
public CueTextBox()
: base()
{
_cueText = string.Empty;
}
protected virtual void OnCueTextChanged(EventArgs e)
{
this.Invalidate(true);
if (this.CueTextChanged != null)
this.CueTextChanged(this, e);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (string.IsNullOrEmpty(this.Text.Trim()) && !string.IsNullOrEmpty(this.CueText) && !this.Focused)
{
Point startingPoint = new Point(0, 0);
StringFormat format = new StringFormat();
Font font = new Font(this.Font.FontFamily.Name, this.Font.Size, FontStyle.Italic);
if (this.RightToLeft == RightToLeft.Yes)
{
format.LineAlignment = StringAlignment.Far;
format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
}
e.Graphics.DrawString(CueText, font, Brushes.Gray, this.ClientRectangle, format);
}
}
const int WM_PAINT = 0x000F;
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_PAINT)
{
this.OnPaint(new PaintEventArgs(Graphics.FromHwnd(m.HWnd), this.ClientRectangle));
}
}
}
现在,所有你需要的是一套“CueText”属性到你想要的初始值,你就大功告成了!
好的提示,但对新手来说很复杂:) – 2012-02-13 20:46:54
这种方式你不修改文本框的'文本'属性,这可能会导致意想不到的结果。在我的解决方案中,文本仅在文本框区域上绘制,并且您可以使用Text属性而不用担心 – Nissim 2012-06-26 08:27:59
我个人喜欢您的解决方案:) – 2012-06-26 09:19:45
如果你正在使用的WinForms,你可以在你的情况下,加水痕(用户名)到文本框...... – 2012-02-12 09:32:25
是否文本消失一旦你点击像SO的搜索框那样的框? – 2012-02-12 09:48:05
我很高兴它为你工作:) – 2012-02-12 14:37:38