I have a custom ValidationRule that requires access to the ViewModel in order to validate a supplied value in conjunction with other properties of the ViewModel. I previously tr
After some research, I have come up with the following code which works exactly as the DataErrorValidationRule works.
class VJValidationRule : System.Windows.Controls.ValidationRule
{
public VJValidationRule()
{
//we need this so that BindingExpression is sent to Validate method
base.ValidationStep = System.Windows.Controls.ValidationStep.UpdatedValue;
}
public override System.Windows.Controls.ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
System.Windows.Controls.ValidationResult result = System.Windows.Controls.ValidationResult.ValidResult;
System.Windows.Data.BindingExpression bindingExpression = value as System.Windows.Data.BindingExpression;
System.ComponentModel.IDataErrorInfo source = bindingExpression.DataItem as System.ComponentModel.IDataErrorInfo;
if (source != null)
{
string msg = source[bindingExpression.ParentBinding.Path.Path];
result = new System.Windows.Controls.ValidationResult(msg == null, msg);
}
return result;
}