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

前端 未结 10 2011
眼角桃花
眼角桃花 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:21

    this is it you need to check the HasError control property from the code behaind

    and do this code in the save button click

     BindingExpression bexp = this.TextBox1.GetBindingExpression(TextBox.TextProperty);
    bexp.UpdateSource(); // this to refresh the binding and see if any error exist 
    bool hasError = bexp.HasError;  // this is boolean property indique if there is error 
    
    MessageBox.Show(hasError.ToString());
    
    0 讨论(0)
  • 2020-11-28 10:21

    just inhert your ViewModel from System.ComponentModel.IDataErrorInfo for Validate and from INotifyPropertyChanged to notify button

    make property:

        public bool IsValid
        {
            get
            {
                if (this.FloorPlanName.IsEmpty())
                    return false;
                return true;
            }
        }
    

    in xaml, connect it to button

    <Button Margin="4,0,0,0" Style="{StaticResource McVMStdButton_Ok}" Click="btnDialogOk_Click" IsEnabled="{Binding IsValid}"/>
    

    in the IDataErrorInfo overrides, notify btutton

    public string this[string columnName]{
            get
            {
                switch (columnName)
                {
                    case "FloorPlanName":
                        if (this.FloorPlanName.IsEmpty())
                        {
                            OnPropertyChanged("IsValid");
                            return "Floor plan name cant be empty";
                        }
                        break;
                }
            }
    }
    
    0 讨论(0)
  • 2020-11-28 10:26

    I've tried several of the solutions stated above; however, none of them worked for me.

    My Simple Problem

    I have a simple input window that request a URI from the user, if the TextBox value isn't a valid Uri then the Okay button should be disabled.

    My Simple Solution

    Here is what worked for me:

    CommandBindings.Add(new CommandBinding(AppCommands.Okay,
                (sender, args) => DialogResult = true,
                (sender, args) => args.CanExecute = !(bool) _uriTextBoxControl.GetValue(Validation.HasErrorProperty)));
    
    0 讨论(0)
  • 2020-11-28 10:27

    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.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-11-28 10:32
    int count = 0;
    
    private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)
    {
        if (e.Action == ValidationErrorEventAction.Added)
        {
            button1.IsEnabled = false;
            count++;
        }
        if (e.Action == ValidationErrorEventAction.Removed)
        {                
            count--;
            if (count == 0) button1.IsEnabled = true;
        }
    }
    
    0 讨论(0)
提交回复
热议问题