【发布时间】:2017-11-29 16:17:58
【问题描述】:
我正在使用以下函数在文本框上创建占位符效果,并且效果很好。
现在,我想在多个文本框上使用它。因为我只有一个盒子,placeholder 变量就足够了。对于多个框,我需要多个占位符字符串。有没有办法将自定义属性添加到文本框,以便我可以从占位符函数中访问它?
public MainForm()
{
InitializeComponent();
Placeholder_Show(DomainBox, null);
}
public static string placeholder = "example.com";
private void Placeholder_Hide(object sender, EventArgs e)
{
var box = sender as TextBox;
if (box.Text == placeholder)
{
box.Text = "";
box.ForeColor = Color.Black;
box.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
}
}
private void Placeholder_Show(object sender, EventArgs e)
{
var box = sender as TextBox;
if (string.IsNullOrEmpty(box.Text))
{
box.Text = placeholder;
box.ForeColor = Color.Gray;
box.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
}
}
所需代码(示例):
textBox1.placeholder = "some";
textBox2.placeholder = "string";
private void Placeholder_Hide(object sender, EventArgs e)
{
var box = sender as TextBox;
if (box.Text == box.placeholder) // placeholders are associated with boxes
{
box.Text = "";
box.ForeColor = Color.Black;
box.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
}
}
private void Placeholder_Show(object sender, EventArgs e)
{
var box = sender as TextBox;
if (string.IsNullOrEmpty(box.Text))
{
box.Text = box.placeholder;
box.ForeColor = Color.Gray;
box.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
}
}
我对 C# 不是很熟悉。也许,有更好的方法来解决这个问题。
【问题讨论】:
-
你可以扩展
TextBox类并在你的新类中实现它。
标签: c# textbox placeholder