/// <summary> /// Determines whether [is in edit mode update] [the specified obj]. /// </summary> /// <param name="obj">The obj.</param> /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void IsInEditModeUpdate(DependencyObject obj, DependencyPropertyChangedEventArgs e) { EditableTextBlock textBlock = obj as EditableTextBlock; if (null != textBlock) { //Get the adorner layer of the uielement (here TextBlock) AdornerLayer layer = AdornerLayer.GetAdornerLayer(textBlock); //If the IsInEditMode set to true means the user has enabled the edit mode then //add the adorner to the adorner layer of the TextBlock. if (textBlock.IsInEditMode) { if (null == textBlock._adorner) { textBlock._adorner = new EditableTextBlockAdorner(textBlock); //Events wired to exit edit mode when the user presses Enter key or leaves the control. textBlock._adorner.TextBoxKeyUp += textBlock.TextBoxKeyUp; textBlock._adorner.TextBoxLostFocus += textBlock.TextBoxLostFocus; } layer.Add(textBlock._adorner); } else { //Remove the adorner from the adorner layer. Adorner[] adorners = layer.GetAdorners(textBlock); if (adorners != null) { foreach (Adorner adorner in adorners) { if (adorner is EditableTextBlockAdorner) { layer.Remove(adorner); } } } //Update the textblock's text binding. BindingExpression expression = textBlock.GetBindingExpression(TextProperty); if (null != expression) { expression.UpdateTarget(); } } } }
public EditableTextBlockAdorner(EditableTextBlock adornedElement) : base(adornedElement) { _collection = new VisualCollection(this); _textBox = new TextBox() { FontSize = adornedElement.FontSize, FontWeight = adornedElement.FontWeight, FontStyle = adornedElement.FontStyle }; _textBlock = adornedElement; Binding binding = new Binding("Text") { Source = adornedElement }; _textBox.SetBinding(TextBox.TextProperty, binding); _textBox.AcceptsReturn = true; _textBox.MaxLength = adornedElement.MaxLength; _textBox.KeyUp += _textBox_KeyUp; _collection.Add(_textBox); }