TextBoxWithPlaceHolder.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Drawing;
  3. using System.Windows.Forms;
  4. namespace UAS_MES_NEW.CustomControl.TextBoxWithIcon
  5. {
  6. public partial class TextBoxWithPlaceHolder : UserControl
  7. {
  8. //记录一个PlaceHolder,第一次对这个文本框赋的值
  9. string PlaceHolder1;
  10. public string PlaceHolder
  11. {
  12. get
  13. {
  14. return PlaceHolder1;
  15. }
  16. set
  17. {
  18. PlaceHolder1 = value;
  19. }
  20. }
  21. public override string Text
  22. {
  23. get
  24. {
  25. if (TextBox.Text == PlaceHolder1)
  26. {
  27. return "";
  28. }
  29. return TextBox.Text;
  30. }
  31. set
  32. {
  33. TextBox.Text = value;
  34. }
  35. }
  36. public delegate void OnTextChange(object sender, EventArgs e);
  37. public event OnTextChange UserControlTextChanged;
  38. public TextBoxWithPlaceHolder()
  39. {
  40. InitializeComponent();
  41. try { UAS_MES_NEW.I18n.LanguageManager.Localize(this); } catch { }
  42. Load += TextBoxWithPlaceHolder_Load;
  43. }
  44. private void TextBoxWithPlaceHolder_Load(object sender, System.EventArgs e)
  45. {
  46. TextBox.Text = PlaceHolder1;
  47. TextBox.ForeColor = Color.Silver;
  48. }
  49. private void TextBox_Leave(object sender, System.EventArgs e)
  50. {
  51. //失去焦点的时候如果文本框存在内容就把文字变色
  52. TextBox.BackColor = Color.White;
  53. if (TextBox.Text == "")
  54. {
  55. TextBox.ForeColor = Color.Silver;
  56. TextBox.Text = PlaceHolder1;
  57. }
  58. }
  59. private void TextBox_Enter(object sender, System.EventArgs e)
  60. {
  61. TextBox.ForeColor = Color.Black;
  62. if (TextBox.Text == PlaceHolder1)
  63. {
  64. TextBox.Text = "";
  65. }
  66. else TextBox.ForeColor = Color.Black;
  67. }
  68. private void TextBox_TextChanged(object sender, EventArgs e)
  69. {
  70. UserControlTextChanged?.Invoke(sender, new EventArgs());
  71. }
  72. }
  73. }