EditableTextBlockAdorner.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System.Windows;
  2. using System.Windows.Controls;
  3. using System.Windows.Data;
  4. using System.Windows.Documents;
  5. using System.Windows.Input;
  6. using System.Windows.Media;
  7. namespace GeekDesk.EditTextBlock
  8. {
  9. /// <summary>
  10. /// Adorner class which shows textbox over the text block when the Edit mode is on.
  11. /// </summary>
  12. public class EditableTextBlockAdorner : Adorner
  13. {
  14. private readonly VisualCollection _collection;
  15. private readonly TextBox _textBox;
  16. private readonly TextBlock _textBlock;
  17. public EditableTextBlockAdorner(EditableTextBlock adornedElement)
  18. : base(adornedElement)
  19. {
  20. _collection = new VisualCollection(this);
  21. _textBox = new TextBox();
  22. _textBlock = adornedElement;
  23. Binding binding = new Binding("Text") { Source = adornedElement };
  24. _textBox.SetBinding(TextBox.TextProperty, binding);
  25. _textBox.AcceptsReturn = true;
  26. _textBox.MaxLength = adornedElement.MaxLength;
  27. _textBox.KeyUp += _textBox_KeyUp;
  28. _collection.Add(_textBox);
  29. }
  30. void _textBox_KeyUp(object sender, KeyEventArgs e)
  31. {
  32. if (e.Key == Key.Enter)
  33. {
  34. _textBox.Text = _textBox.Text.Replace("\r\n", string.Empty);
  35. BindingExpression expression = _textBox.GetBindingExpression(TextBox.TextProperty);
  36. if (null != expression)
  37. {
  38. expression.UpdateSource();
  39. }
  40. }
  41. }
  42. protected override Visual GetVisualChild(int index)
  43. {
  44. return _collection[index];
  45. }
  46. protected override int VisualChildrenCount
  47. {
  48. get
  49. {
  50. return _collection.Count;
  51. }
  52. }
  53. protected override Size ArrangeOverride(Size finalSize)
  54. {
  55. _textBox.Arrange(new Rect(0, 0, _textBlock.DesiredSize.Width + 50, _textBlock.DesiredSize.Height * 1.5));
  56. _textBox.Focus();
  57. return finalSize;
  58. }
  59. protected override void OnRender(DrawingContext drawingContext)
  60. {
  61. drawingContext.DrawRectangle(null, new Pen
  62. {
  63. Brush = Brushes.Gold,
  64. Thickness = 2
  65. }, new Rect(0, 0, _textBlock.DesiredSize.Width + 50, _textBlock.DesiredSize.Height * 1.5));
  66. }
  67. public event RoutedEventHandler TextBoxLostFocus
  68. {
  69. add
  70. {
  71. _textBox.LostFocus += value;
  72. }
  73. remove
  74. {
  75. _textBox.LostFocus -= value;
  76. }
  77. }
  78. public event KeyEventHandler TextBoxKeyUp
  79. {
  80. add
  81. {
  82. _textBox.KeyUp += value;
  83. }
  84. remove
  85. {
  86. _textBox.KeyUp -= value;
  87. }
  88. }
  89. }
  90. }