如何为文本框实现绑定验证?
<TextBox Name="textBox1" Width="50" FontSize="15"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}"
Grid.Row="1" Grid.Column="1" Margin="2">
<TextBox.Text>
<Binding Path="Age" Source="{StaticResource ods}"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
// What should I write here?
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我应该在验证规则中写什么?
答案 0 :(得分:3)
以下示例显示了AgeRangeRule的实现,它继承自ValidationRule并覆盖Validate方法。对值调用Int32.Parse()方法以确保它不包含任何无效字符。 Validate方法返回一个ValidationResult,它根据解析过程中是否捕获到异常以及age值是否超出下限和上限来指示该值是否有效。
public class AgeRangeRule : ValidationRule
{
private int _min;
private int _max;
public AgeRangeRule()
{
}
public int Min
{
get { return _min; }
set { _min = value; }
}
public int Max
{
get { return _max; }
set { _max = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
int age = 0;
try
{
if (((string)value).Length > 0)
age = Int32.Parse((String)value);
}
catch (Exception e)
{
return new ValidationResult(false, "Illegal characters or " + e.Message);
}
if ((age < Min) || (age > Max))
{
return new ValidationResult(false,
"Please enter an age in the range: " + Min + " - " + Max + ".");
}
else
{
return new ValidationResult(true, null);
}
}
}
答案 1 :(得分:2)
要扩展Cornel的答案,以下是您将使用其示例代码的相关XAML:
<TextBox Name="textBox1" Width="50" FontSize="15"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}"
Grid.Row="1" Grid.Column="1" Margin="2"> <TextBox.Text>
<Binding Path="Age" Source="{StaticResource ods}"
UpdateSourceTrigger="PropertyChanged" >
<Binding.ValidationRules>
<c:AgeRangeRule Min="21" Max="130"/>
</Binding.ValidationRules>
</Binding></TextBox.Text></TextBox>
总而言之,您创建自定义Validation类,在XAML代码中引用它,然后使用初始化的必要属性实现它。