TextBox user control: Setting Text in OnPropertyChanged cancels binding
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.)