TextBoxEx.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Media;
  9. namespace PDF_Office.CustomControl
  10. {
  11. /// <summary>
  12. /// 带预文本和圆角的textbox
  13. /// </summary>
  14. public class TextBoxEx : TextBox
  15. {
  16. static TextBoxEx()
  17. {
  18. DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxEx), new FrameworkPropertyMetadata(typeof(TextBoxEx)));
  19. }
  20. ~TextBoxEx()
  21. {
  22. var btn = base.GetTemplateChild("PART_BtnClear") as Button;
  23. if (btn != null)
  24. {
  25. //一定要取消事件挂载,否则可能无法被GC回收
  26. btn.Click -= Btn_Click;
  27. }
  28. }
  29. public override void OnApplyTemplate()
  30. {
  31. //需要配合特定的Style才可用
  32. var btn = base.GetTemplateChild("PART_BtnClear") as Button;
  33. if(btn!=null)
  34. {
  35. btn.Click += Btn_Click;
  36. }
  37. base.OnApplyTemplate();
  38. }
  39. private void Btn_Click(object sender, RoutedEventArgs e)
  40. {
  41. this.Text = "";
  42. this.Focus();
  43. }
  44. public string PlaceholderText
  45. {
  46. get { return (string)GetValue(PlaceholderTextProperty); }
  47. set { SetValue(PlaceholderTextProperty, value); }
  48. }
  49. public static readonly DependencyProperty PlaceholderTextProperty
  50. = DependencyProperty.Register("PlaceholderText", typeof(string), typeof(TextBoxEx), null);
  51. public CornerRadius CornerRadius
  52. {
  53. get { return (CornerRadius)GetValue(CornerRadiusProperty); }
  54. set { SetValue(CornerRadiusProperty, value); }
  55. }
  56. public static readonly DependencyProperty CornerRadiusProperty =
  57. DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(TextBoxEx), new PropertyMetadata(new CornerRadius(4)));
  58. public Brush PlaceholderForeground
  59. {
  60. get { return (Brush)GetValue(PlaceholderForegroundProperty); }
  61. set { SetValue(PlaceholderForegroundProperty, value); }
  62. }
  63. public static readonly DependencyProperty PlaceholderForegroundProperty =
  64. DependencyProperty.Register("PlaceholderForeground", typeof(Brush), typeof(TextBoxEx), new PropertyMetadata(new SolidColorBrush((Color)ColorConverter.ConvertFromString("#94989C"))));
  65. public Brush MouseOverForeground
  66. {
  67. get
  68. {
  69. return (Brush)GetValue(MouseOverForegroundProperty);
  70. }
  71. set { SetValue(MouseOverForegroundProperty, value); }
  72. }
  73. public static readonly DependencyProperty MouseOverForegroundProperty =
  74. DependencyProperty.Register("MouseOverForeground", typeof(Brush), typeof(TextBoxEx), new PropertyMetadata(new SolidColorBrush(Colors.Transparent)));
  75. }
  76. }