I had an issue with pulling ValidationRules into the ViewModel in the WPF MVVM pattern as this is a UI construct.
So to get around this I created IRule which is a simple interface:
public interface IRule
object Validate(object value);
Then to produce a validation rule it just implements this interface instead of ValidationRule.If there is an error it returns it, otherwise it returns null.
A second class, Validator, just wraps the IRule but implements ValidationRule.
public class Validator : ValidationRuleIn my scenario I am dynamicall building the bindings in the code-behind of the view as I am adding columns to a DataGrid.
private readonly IRule m_rule;
public Validator(IRule rule)
m_rule = rule;
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
object error = m_rule.Validate(value);
return new ValidationResult(error == null, error);
When the binding is setup it is bound to the validator that wraps the required IRule.
binding.ValidationRules.Add(new Validator(myIRule));Nice and simple and abstracts the rule away from the UI. I'm sure there will be a way to do this in XAML.