using System; using System.Drawing; using System.Windows.Forms; namespace UAS_MES_NEW.CustomControl.TextBoxWithIcon { public partial class TextBoxWithPlaceHolder : UserControl { //记录一个PlaceHolder,第一次对这个文本框赋的值 string PlaceHolder1; public string PlaceHolder { get { return PlaceHolder1; } set { PlaceHolder1 = value; } } public override string Text { get { if (TextBox.Text == PlaceHolder1) { return ""; } return TextBox.Text; } set { TextBox.Text = value; } } public delegate void OnTextChange(object sender, EventArgs e); public event OnTextChange UserControlTextChanged; public TextBoxWithPlaceHolder() { InitializeComponent(); Load += TextBoxWithPlaceHolder_Load; } private void TextBoxWithPlaceHolder_Load(object sender, System.EventArgs e) { TextBox.Text = PlaceHolder1; TextBox.ForeColor = Color.Silver; } private void TextBox_Leave(object sender, System.EventArgs e) { //失去焦点的时候如果文本框存在内容就把文字变色 TextBox.BackColor = Color.White; if (TextBox.Text == "") { TextBox.ForeColor = Color.Silver; TextBox.Text = PlaceHolder1; } } private void TextBox_Enter(object sender, System.EventArgs e) { TextBox.ForeColor = Color.Black; if (TextBox.Text == PlaceHolder1) { TextBox.Text = ""; } else TextBox.ForeColor = Color.Black; } private void TextBox_TextChanged(object sender, EventArgs e) { UserControlTextChanged?.Invoke(sender, new EventArgs()); } } }