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
?