2

ユーザーが TextBox.MaxLength プロパティで許可されているよりも多くの文字を入力しようとしたときに、視覚的および聴覚的な警告を発する方法はありますか?

4

1 に答える 1

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