HintTextBehavior.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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.Interactivity;
  9. using System.Windows.Media;
  10. namespace PixiEditor.Helpers.Behaviours
  11. {
  12. class HintTextBehavior : Behavior<TextBox>
  13. {
  14. private Brush _textColor;
  15. public string Hint
  16. {
  17. get { return (string)GetValue(HintProperty); }
  18. set { SetValue(HintProperty, value); }
  19. }
  20. // Using a DependencyProperty as the backing store for Hint. This enables animation, styling, binding, etc...
  21. public static readonly DependencyProperty HintProperty =
  22. DependencyProperty.Register("Hint", typeof(string), typeof(HintTextBehavior), new PropertyMetadata(string.Empty));
  23. protected override void OnAttached()
  24. {
  25. base.OnAttached();
  26. AssociatedObject.GotFocus += AssociatedObject_GotFocus;
  27. AssociatedObject.LostFocus += AssociatedObject_LostFocus;
  28. _textColor = AssociatedObject.Foreground;
  29. SetHint(true);
  30. }
  31. private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e)
  32. {
  33. if(string.IsNullOrEmpty(AssociatedObject.Text) == true)
  34. {
  35. SetHint(true);
  36. }
  37. }
  38. private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e)
  39. {
  40. if(AssociatedObject.Text == Hint)
  41. {
  42. SetHint(false);
  43. }
  44. }
  45. private void SetHint(bool active)
  46. {
  47. if (active == true)
  48. {
  49. AssociatedObject.Foreground = (SolidColorBrush)new BrushConverter().ConvertFromString("#7B7B7B");
  50. AssociatedObject.Text = Hint;
  51. }
  52. else
  53. {
  54. AssociatedObject.Text = string.Empty;
  55. AssociatedObject.Foreground = _textColor;
  56. }
  57. }
  58. protected override void OnDetaching()
  59. {
  60. base.OnDetaching();
  61. AssociatedObject.LostFocus -= AssociatedObject_LostFocus;
  62. AssociatedObject.GotFocus -= AssociatedObject_GotFocus;
  63. }
  64. }
  65. }