Search code examples
wpfbindingidataerrorinfo

Is there a way to set default binding option in base class?


I have MyTextBox which is derived from TextBox. I want to set Binding Option ValidatesOnDataErrors = True of TextProperty in MyTextBox so that whenever I use this control ValidatesOnDataErrors is initialized with True.

This is my code :

public class MyTextBox:MyBaseTextBox
{
    public MyTextBox()
    {
        MaxLength = 45;
    }

    protected override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property == TextProperty)
        {
            Binding b = BindingOperations.GetBinding(this, TextProperty);
            if (b != null)
            {
                b.ValidatesOnDataErrors = true;
            }                
        }
    }
}

And I always get the exception :

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: Binding cannot be changed after it has been used.

Am I missing something ?


Solution

  • I think what you need is special binding not special textbox.

    Have a look here: Set ValidatesOnDataErrors for all bindings programmatically

    in WPF you can't change binding once it has been used.

    to make your code work you'd have to clear the binding first and then add a new one with ValidatesOnDataErrors set to true, but that sounds like a messy way...