Using WPF Validation rules and the disabling of a 'Save' button

前端 未结 10 2052
眼角桃花
眼角桃花 2020-11-28 09:54

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


                            


        
10条回答
  •  执念已碎
    2020-11-28 10:32

    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).

提交回复
热议问题