2

当用户尝试键入的字符数超过 TextBox.MaxLength 属性所允许的字符数时,是否会发出可见和可听的警告?

4

1 回答 1

0

您可以在 Binding 上添加 ValidationRule。如果验证失败,TextBox会使用默认的ErrorTemplate,否则你也可以自定义...

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>
于 2011-06-15T07:26:05.807 回答