当用户尝试输入的字符多于TextBox.MaxLength属性所允许的字符数时,是否还会触发可见和声音警告?
答案 0 :(得分:0)
您可以在Binding上添加ValidationRule。如果验证失败,默认的ErrorTemplate将用于TextBox,否则您也可以自定义它...
ValidatonRule的示例:
class MaxLengthValidator : ValidationRule
{
public MaxLengthValidator()
{
}
public int MaxLength
{
get;
set;
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value.ToString().Length <= MaxLength)
{
return new ValidationResult(true, null);
}
else
{
//Here you can also play the sound...
return new ValidationResult(false, "too long");
}
}
}
以及如何将其添加到绑定中:
<TextBlock x:Name="target" />
<TextBox Height="23" Name="textBox1" Width="120">
<TextBox.Text>
<Binding Mode="OneWayToSource" ElementName="target" Path="Text" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:MaxLengthValidator MaxLength="10" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>