Tuesday, May 3, 2011

Using WPF Validation rules and disabling a 'Save' button

I have a page where a few textboxes cannot be empty before clicking a Save button.

<TextBox...

                <TextBox.Text>
                    <Binding Path ="LastName" UpdateSourceTrigger="PropertyChanged">

                        <Binding.ValidationRules>
                            <local:StringRequiredValidationRule />
                        </Binding.ValidationRules>                              
                    </Binding>
                </TextBox.Text>

My rule works. I have a red border around my textbox until I enter a value. So now I want to add this validation rule to my other text boxes.

Now, how do I disable the Save button until the page has no errors? I do not know what to check to see if there are any validation errors.

From stackoverflow
  • You want to use Validation.HasError attached property.

    Along the same lines Josh Smith has an interesting read on Binding to (Validation.Errors)[0] without Creating Debug Spew.

  • On the codebehind for the view you could wireup the Validation.ErrorEvent like so;

    this.AddHandler(Validation.ErrorEvent,new RoutedEventHandler(OnErrorEvent));
    

    And then

    private int errorCount;
    private void OnErrorEvent(object sender, RoutedEventArgs e)
    {
        var validationEventArgs = e as ValidationErrorEventArgs;
        if (validationEventArgs  == null)
            throw new Exception("Unexpected event args");
        switch(validationEventArgs.Action)
        {
            case ValidationErrorEventAction.Added:
                {
                    errorCount++; break;
                }
            case ValidationErrorEventAction.Removed:
                {
                    errorCount--; break;
                }
            default:
                {
                    throw new Exception("Unknown action");
                }
        }
        Save.IsEnabled = errorCount == 0;
    }
    

    This makes the assumption that you will get notified of the removal (which won't happen if you remove the offending element while it is invalid).

0 comments:

Post a Comment