开发者

WPF TextBox MaxLength Warning

Is there anyway to fire a visible and audible warning when a user attempts开发者_StackOverflow中文版 to type more characters than allowed with the TextBox.MaxLength property?


You can add a ValidationRule on the Binding. If the validation will fail, the default ErrorTemplate will be used for the TextBox, otherwise you can also customize it...

example of the 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");
        }

    }
}

and how to add it to the binding:

<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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜