I am trying to create a validation rule for a given control (in this scenario, it is the TextBox).
I am not able to obtain a successful Binding to the property of an object, although appropriate steps were taken: ValidationRule and DepedencyProperty are taken advantage of.
Kindly find code below. A side note is that "Is Required" in the custom Validation class is always False, unless I explicitly set the value in the XAML (no Binding, as per "Is Ranged" parameter).
Alternative is to use IDataErrorInfo interface, but I would like to stick to the ValidationRules.
Any tips and suggestions are appreciated.
Thank you in advance :)
XAML Code:
Expand|Select|Wrap|Line Numbers
- <TextBox Style="{StaticResource ValidationError}" LostFocus="ForceValidationCheck"
- Visibility="{Binding Type, Converter={StaticResource Visibility}, ConverterParameter='Number'}"
- IsEnabled="{Binding RelativeSource={x:Static RelativeSource.Self}, Converter={StaticResource IsEnabled}}">
- <TextBox.Text>
- <Binding Path="Value">
- <Binding.ValidationRules>
- <validation:NumericValidation>
- <validation:NumericValidation.Dependency>
- <validation:NumericDependency IsRequired="{Binding Path=IsRequired}" IsRanged="True" Min="5"/>
- </validation:NumericValidation.Dependency>
- </validation:NumericValidation>
- </Binding.ValidationRules>
- </Binding>
- </TextBox.Text>
- </TextBox>
Expand|Select|Wrap|Line Numbers
- public NumericDependency Dependency { get; set; }
- public override ValidationResult Validate(object value, CultureInfo cultureInfo)
- {
- isRequired = Dependency.IsRequired;
- }
Expand|Select|Wrap|Line Numbers
- public static readonly DependencyProperty IsRequiredProperty =
- DependencyProperty.Register("IsRequired", typeof(bool), typeof(NumericDependency), new UIPropertyMetadata(default(bool)));
- public bool IsRequired
- {
- get
- {
- return (bool) GetValue(IsRequiredProperty);
- }
- set
- {
- SetValue(IsRequiredProperty, value);
- }
- }