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).
Any tips and suggestions are appreciated.
Thank you in advance :)
XAML Code:
<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>
Validation Class:
public NumericDependency Dependency { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
isRequired = Dependency.IsRequired;
}
Validation Dependency Class:
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);
}
}
You can use a proxy. It will allow you to bind a Property to your ValidationRule.
Here is a code sample that may help you :
<Utils:Proxy In="{Binding IsRequired, Mode=OneWay,UpdateSourceTrigger=PropertyChanged}" Out="{Binding ElementName=numericValidationRule, Path=IsRequired}" />
<TextBox>
<TextBox.Text>
<Binding Path="Value">
<Binding.ValidationRules>
<NumericValidation x:Name="numericValidationRule" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>