Search code examples
wpfmvvmvalidationerror

Wpf clear disabled TextBox.Text when there is validation error


I have three textboxes with text binded to three properties. I need to disable two textboxes, when i type in the third one. And i have to clear the value of the disabled textboxes.

`

 <TextBox Text="{Binding TextProperty1}"  IsEnabled="{Binding T1Enabled}"/>
 <TextBox Text="{Binding TextProperty2}"  IsEnabled="{Binding T2Enabled}"/>
 <TextBox Text="{Binding TextProperty3}"  IsEnabled="{Binding T3Enabled}"/>

`

T1-3Enabled is a property with only getters, and i raise propertychanged on textboxes' lost focus command. When these properties refreshed i clear the binded propertes of the disabled textboxes (TextProperty1-3).

But, when some of the disabled textboxes have validation errors, the source property is cleared, but the textbox.text is not.

How can i solve this in mvvm? I dont want to set textbox.text.

I hope the problem is clear. Thanks for any help or other solution.


Solution

  • I solved the problem with a derived textbox class.

    public class MyTextBox : TextBox
    {
        public MyTextBox()
        {
            IsEnabledChanged += MyTextBox_IsEnabledChanged;
        }
    
        private void MyTextBox_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if(e.NewValue is bool)
                if (!(bool)e.NewValue)
                    Text = string.Empty;
        }
    }