我的Custom ValidationRule存在问题。
这是我的.cs文件:
public class LengthValidationRule : ValidationRule
{
private int _min;
private int _max;
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 length = value.ToString().Length;
if ((length < Min) || (length > Max))
{
return new ValidationResult(false,
Resources.Strings.ProperFieldLength + Min + " - " + Max + ".");
}
else
{
return new ValidationResult(true, null);
}
}
}
我在.xaml文件中使用它有两种情况
首先(工作):
<TextBox x:Name="usernameTextBox"
Grid.Row="0"
Grid.Column="1"
IsEnabled="{Binding InEdit, Mode=OneWay}">
<TextBox.Text>
<Binding Path="SelectedUser.Login"
Mode="TwoWay"
NotifyOnValidationError="True"
ValidatesOnExceptions="True">
<Binding.ValidationRules>
<Validation:LengthValidationRule Min="8" Max="20"/>
<Validation:RegexValidationRule RegEx="^[a-zA-Z0-9]+$"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
第二个(不工作 - 甚至没有激活验证器):
<TextBox x:Name="nameTextBox"
Grid.Row="0"
Grid.Column="1"
IsEnabled="{Binding InEdit, Mode=OneWay}">
<TextBox.Text>
<Binding Path="SelectedUser.Acceptor.Name"
Mode="TwoWay"
NotifyOnValidationError="True"
ValidatesOnExceptions="True">
<Binding.ValidationRules>
<Validation:LengthValidationRule Min="1" Max="10"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我发现了,这个错误的原因是这个“嵌套”绑定:
Binding Path="SelectedUser.Acceptor.Name"
但我不知道如何让它发挥作用。