Textbox not setting the value as null when the user cleans the text field in WPF

Viewed 355

I have the next textbox:

<TextBox FontSize="10">
    <TextBox.Text>
        <Binding Path="EstatusAdministrativo" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <validations:IsRequiredValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

This textbox is binded to a variable in the ViewModel that looks like this:

private string _EstatusAdministrativo;
public string EstatusAdministrativo {
 get {
  return _EstatusAdministrativo;
 }
 set {
  _EstatusAdministrativo = value;
  OnPropertyChanged();
 }
}

The validation inside of the textbox looks like this:

public class IsRequiredValidationRule: ValidationRule {
 public override ValidationResult Validate(object value, CultureInfo cultureInfo) {
  string strValue = Convert.ToString(value);
  if (string.IsNullOrWhiteSpace(strValue))
   return new ValidationResult(false, $ "Por favor llenar este campo.");
  return new ValidationResult(true, null);
 }
}

When I delete all the characters in the textbox, the value of EstatusAdministrativos is not setting as null. It doesn't trigger the set method when I clean the textbox. Why is this happening and how can I solve it?

3 Answers

The source property isn't set when the validation rules fails unless you set the ValidationStep property to UpdatedValue:

<validations:IsRequiredValidationRule ValidationStep="UpdatedValue" />

This will cause the validation rule to run after the source property has been set. You can read more about this in this blog post.

If you need more control, you should get rid of the validation rule and implement the INotifyDataErrorInfo interface in your view model class.

instead of

return new ValidationResult(true, null);

you should call

return ValidationResult.ValidResult;
Related