TextBox user control: Setting Text in OnPropertyChanged cancels binding

AxD 661 Reputation points
2021-01-23T00:13:24.013+00:00

I created a WPF user control, derived from TextBox.

In this user control I use the OnPropertyChanged event to check if the new text value is accepted.

If I set the Text property (see below, line 32), binding on my user control is lost.

Why?

How can I avoid losing my Text binding just by manually updating the Text property?

Here's my code:

namespace WPF.Controls  
{  
  public partial class MaskedRegexTextBox : TextBox  
  {  
    public static readonly DependencyProperty MaskProperty = DependencyProperty.Register("Mask", typeof(string), typeof(MaskedRegexTextBox), new FrameworkPropertyMetadata(null) { BindsTwoWayByDefault = false, DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, IsAnimationProhibited = true });  



    public string? Mask  
    {  
      get => (string?)GetValue(MaskProperty);  
      set => SetValue(MaskProperty, value);  
    }  


    public MaskedRegexTextBox()  
    {  
      InitializeComponent();  
    }  



    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)  
    {  
      base.OnPropertyChanged(e);  

      if (e.Property == TextProperty)  
      {  
        if (!(string.IsNullOrWhiteSpace(Mask) || string.IsNullOrWhiteSpace((string?)e.NewValue) || Regex.IsMatch((string)e.NewValue, $"^{Mask.Trim()}$")))  
        {  
          SystemSounds.Beep.Play();  
          Text = (string?)e.OldValue;  
        }  
        if (SelectionLength == 0) Dispatcher.BeginInvoke(new Action(() => SelectionLength = 1));  
      }  
    }  
  }  
}  

Your help is very much appreciated.

---
(PS: I closed this question after realizing that assigning text to the Text property obviously overwrites the original binding information. I created a new question here, reflecting the new situation and asking how to assign text to a TextBox without losing binding information.)

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,199 questions
0 comments No comments
{count} votes