WPF TextBox MaxLength警告

|| 当用户尝试键入超出TextBox.MaxLength属性所允许的字符时,是否仍会发出可见和可听的警告?     
已邀请:
        您可以在绑定上添加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>
    

要回复问题请先登录注册