private void AddEnterpriseValidationRule(FrameworkElement element, Binding binding, DependencyProperty dp)
{
if (element.DataContext == null)
return;
foreach (ValidationRule validationRule in binding.ValidationRules)
{
if (validationRule is EnterpriseValidationRule)
return; //enterprise validation rule already exists for this binding, no need to add again
}
EnterpriseValidationRule rule = new EnterpriseValidationRule();
Type propertyType = element.DataContext.GetType();
rule.SourceTypeName = propertyType.AssemblyQualifiedName;
rule.PropertyName = binding.Path.Path;
if (rule.PropertyName.Length == 0)
return; //don't validate XML bindings
PropertyInfo propertyInfo = propertyType.GetProperty(rule.PropertyName);
//validate property paths, e.g. Address.Street
int dot = rule.PropertyName.IndexOf('.');
while (dot >= 0)
{
string propertyName = rule.PropertyName.Substring(0, dot);
propertyInfo = propertyType.GetProperty(propertyName);
if (propertyInfo == null)
return;
propertyType = propertyInfo.PropertyType;
rule.SourceTypeName = propertyType.AssemblyQualifiedName;
rule.PropertyName = rule.PropertyName.Substring(dot + 1);
dot = rule.PropertyName.IndexOf('.');
}
if (propertyInfo == null)
return;
rule.RulesetName = RulesetName;
rule.SpecificationSource = SpecificationSource;
rule.Converter = binding.Converter;
rule.ConverterCulture = binding.ConverterCulture;
rule.ConverterParameter = binding.ConverterParameter;
binding.ValidationRules.Add(rule);
}