I'm trying to add parameters to my custom validation rule. For this I defined a dependency object like this:
public class SettingsValueValidationDependencyObject : DependencyObject
{
public Custom.ValueType ValueTypeForValidation
{
get { return (Custom.ValueType)this.GetValue(ValueTypeForValidationProperty); }
set { this.SetValue(ValueTypeForValidationProperty, value); }
}
public static readonly DependencyProperty ValueTypeForValidationProperty = DependencyProperty.Register("ValueTypeForValidation", typeof(Custom.ValueType), typeof(SettingsValueValidationDependencyObject), new UIPropertyMetadata(Custom.ValueType.Int32Value));
}
My validation rule class looks like this:
public class SettingsValueValidationRule : ValidationRule
{
public SettingsValueValidationDependencyObject SettingsValueValidationDependencyObject
{
get;
set;
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
// validation...
}
}
xaml code:
<DataGridTextColumn Header="Value" Width="150">
<DataGridTextColumn.Binding>
<Binding Path="Value">
<Binding.ValidationRules>
<validators:SettingsValueValidationRule>
<validators:SettingsValueValidationRule.SettingsValueValidationDependencyObject>
<validators:SettingsValueValidationDependencyObject ValueTypeForValidation="{Binding ValueType}"/>
</validators:SettingsValueValidationRule.SettingsValueValidationDependencyObject>
</validators:SettingsValueValidationRule>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
The two properties Value and ValueType both belong to the same object and the DataGrid's ItemsSource is bound to a list of these object. When I edit the Value cell, the ValueTypeForValidation property is always the default value (I also have a column to display the ValueType and its definitely another value). I also tried to update the BindingExpression manually in the Validate method but it won't work. What am I doing wrong?
There is no Binding in ValidationRules.
ValidationRules are not part of LogicalTree and so there is no DataContext to serve as Source in your Binding.
There are however few tricks on the internet how to make a ValidationRule "bindable".
Take a look at this tut: