TextBoxWithPlaceHolder.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. Load += TextBoxWithPlaceHolder_Load;
  42. }
  43. private void TextBoxWithPlaceHolder_Load(object sender, System.EventArgs e)
  44. {
  45. TextBox.Text = PlaceHolder1;
  46. TextBox.ForeColor = Color.Silver;
  47. }
  48. private void TextBox_Leave(object sender, System.EventArgs e)
  49. {
  50. //失去焦点的时候如果文本框存在内容就把文字变色
  51. TextBox.BackColor = Color.White;
  52. if (TextBox.Text == "")
  53. {
  54. TextBox.ForeColor = Color.Silver;
  55. TextBox.Text = PlaceHolder1;
  56. }
  57. }
  58. private void TextBox_Enter(object sender, System.EventArgs e)
  59. {
  60. TextBox.ForeColor = Color.Black;
  61. if (TextBox.Text == PlaceHolder1)
  62. {
  63. TextBox.Text = "";
  64. }
  65. else TextBox.ForeColor = Color.Black;
  66. }
  67. private void TextBox_TextChanged(object sender, EventArgs e)
  68. {
  69. UserControlTextChanged?.Invoke(sender, new EventArgs());
  70. }
  71. }
  72. }