我正在为 XAML 中的各种控件编写验证规则。我想在运行时而不是在 XAML 中将validationRules 附加到控件。我正在考虑使用 Converters 。但任何想法/想法将是实现这一目标的更好方法。
示例代码:
<TextBox Name="txtFirstName" > <TextBox.Text> <Binding Path="FirstName" ValidatesOnDataErrors="True" PropertyChanged" >
<Binding.ValidationRules>
<Binding Converter="{StaticResource validationConverter}"/>
</Binding.ValidationRules>
</Binding>
public class ValidationConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Binding b = new Binding();
b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
b.ValidatesOnDataErrors = true;
b.NotifyOnValidationError = true;
b.ValidationRules.Add(new RangeValidationRule { ErrorMessage = "Error shown from Converter ", MinValue = 10, MaxValue = 50 });
return b;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
谢谢,