WPF TextBox MaxLength警告

时间:2011-06-15 02:33:48

标签: wpf textbox warnings alert maxlength

当用户尝试输入的字符多于TextBox.MaxLength属性所允许的字符数时,是否还会触发可见和声音警告?

1 个答案:

答案 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>