我目前正在C#中的Visual上制作一个Windows应用程序,我正在设法找到一个真正的提示。
我在网上找到了很多关于如何设置文本预设的答案,一些例子甚至显示了如何将文本灰化成占位符,但这不是我想要的。
我想要一个灰色的文本,你不必在那里输入什么东西。所以我希望它的行为像一个HTML占位符,就像堆栈溢出.上的"Search &A“搜索栏一样。
是否有一种简单的方法可以做到这一点,比如在Visual上的设计器中配置textbox的属性?
发布于 2016-04-03 02:08:53
这可能是最丑陋的代码,但我认为你可以改进它。
下面的类只是标准TextBox的一个扩展
class PHTextBox : System.Windows.Forms.TextBox
{
System.Drawing.Color DefaultColor;
public string PlaceHolderText {get;set;}
public PHTextBox(string placeholdertext)
{
// get default color of text
DefaultColor = this.ForeColor;
// Add event handler for when the control gets focus
this.GotFocus += (object sender, EventArgs e) =>
{
this.Text = String.Empty;
this.ForeColor = DefaultColor;
};
// add event handling when focus is lost
this.LostFocus += (Object sender, EventArgs e) => {
if (String.IsNullOrEmpty(this.Text) || this.Text == PlaceHolderText)
{
this.ForeColor = System.Drawing.Color.Gray;
this.Text = PlaceHolderText;
}
else
{
this.ForeColor = DefaultColor;
}
};
if (!string.IsNullOrEmpty(placeholdertext))
{
// change style
this.ForeColor = System.Drawing.Color.Gray;
// Add text
PlaceHolderText = placeholdertext;
this.Text = placeholdertext;
}
}
}
复制/粘贴到名为PHTextBox.cs的新cs文件。
转到您的平面设计师并添加一个TextBox。转到设计器并将文本框的教唆行更改如下:
现在编译,但在进行编译之前,只需确保textbox不是第一个获得焦点的元素。为这件事添加按钮。
发布于 2016-04-03 00:49:21
你试过在文本框上重叠标签吗?
在textbox按键事件上,您可以检查textbox.text的长度并设置标签。
在按键事件..。
MyLabel.Visible = String.IsNullOrEmpty(MyTextBox.Text);
当然,您可能希望设置标签的默认文本,也可以将其设置为灰色。
这个问题是,如果您的表单是可重构的。
您想要实现的不是windows窗体的本机。
发布于 2018-08-10 18:54:44
我知道这是一个老问题,但是我正在寻找一种方法,我发现我的答案是最好的答案(),可以在的中显示提示文本。
1)创建一个类 .cs
文件,例如调用MyExtensions.cs
的命名空间,例如“扩展”。
2)在TextBox
中创建一个名为Init(字符串提示符)的方法,该方法接受要在TextBox
中显示的提示文本。
3),让我停止讨论,给出MyExtensions.cs
的其余代码(整个代码):
MyExtensions.cs
using System.Drawing;
using System.Windows.Forms;
namespace Extensions
{
public static class MyExtensions
{
public static void Init(this TextBox textBox, string prompt)
{
textBox.Text = prompt;
bool wma = true;
textBox.ForeColor = Color.Gray;
textBox.GotFocus += (source, ex) =>
{
if (((TextBox)source).ForeColor == Color.Black)
return;
if (wma)
{
wma = false;
textBox.Text = "";
textBox.ForeColor = Color.Black;
}
};
textBox.LostFocus += (source, ex) =>
{
TextBox t = ((TextBox)source);
if (t.Text.Length == 0)
{
t.Text = prompt;
t.ForeColor = Color.Gray;
return;
}
if (!wma && string.IsNullOrEmpty(textBox.Text))
{
wma = true;
textBox.Text = prompt;
textBox.ForeColor = Color.Gray;
}
};
textBox.TextChanged += (source, ex) =>
{
if (((TextBox)source).Text.Length > 0)
{
textBox.ForeColor = Color.Black;
}
};
}
}
}
现在假设你有三个TextBox
:tbUsername
,tbPassword
,tbConfirm
。
在Form_Load(对象发送方,EventArgs e)方法中,初始化三个文本框,使其具有适当的提示文本消息
using Extensions;
namespace MyApp{
public partial class Form1 : Form{
private void Form1_Load(object sender,
EventArgs e){
tbUsername.Init("Type a username");
tbPassword.Init("Type a password");
tbConfirm.Init("Confirm your password");
}
}
}
享受!:)
https://stackoverflow.com/questions/36380291
复制相似问题