2

I saw:

Using WPF Validation rules and disabling a 'Save' button

Two proposed solutions use IDataErrorInfo or attaching a handler to Validation.ErrorEvent through Validation.AddErrorHandler(). AddErrorHandler takes two parameters, the dependency object and the handler. Since I'm doing this in the ViewModel, and have no reference to the DO, how can I achieve this by using my custom rule for validation.

The validation rule:

public class NameValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {    
        if (string.IsNullOrWhiteSpace(((string)value)))
        {
            return new ValidationResult(false, "Must not be empty");
        }

        return new ValidationResult(true, null);
    }
}

And the control that uses it:

<TextBox>
    <TextBox.Text>
        <Binding Path="Customer.FirstName" UpdateSourceTrigger="LostFocus" ValidatesOnDataErrors="True">
            <Binding.ValidationRules>
                <validators:NameValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

<Button Content="Save" Command="{Binding SaveAddCommand}" CommandParameter="{Binding Customer}"/>

So, is there an 'MVVM' way to change the CanExecute of the SaveAddCommand when the text box validation rule returns false, without needing to supply the dependency object in the code behing to the AddHandler?

Community
  • 1
  • 1
Mefhisto1
  • 2,188
  • 7
  • 34
  • 73

2 Answers2

0

I think this should work:

 public class NameValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (string.IsNullOrWhiteSpace(((string)value)))
            {
                return new ValidationResult(false, "Must not be empty");
               ButtonSave.IsEnabled = false;
            }

            return new ValidationResult(true, null);
        }
    }

I hope it works for you ;)

blueeyes
  • 59
  • 2
  • 10
0

One way to do this is to have your Command implementation Raising CanExecuteChanged this will re query the commands CanExecute method.
If you can your MainViewModel could be aware of the child vm's, like customer, changes, i.e. by creating event on the Customer VM. So when the property is being set in the Customer the MainViewModel can then raise CanExecuteChanged and reevaluate the condition for specified Command. This will eliminate the need for custom validation all together leaving MainViewModel Command controlling the Availability of the button, like WPF expects it to be.
HTH
P.S. Let us know if you need more help, happy coding
EDIT: this is assuming that your MainViewModel has the SaveAddCommand.

XAMlMAX
  • 2,268
  • 1
  • 14
  • 23