WPF 文本框的验证规则

本文关键字:验证 规则 文本 WPF | 更新日期: 2023-09-27 17:55:32

我是新手 WPF.In 我的用户控件,我有 8 个标签及其各自的 8 个文本框,如下所示:

1.Label : abc   2.Label : def
  TextBox1 :        TextBox2 :
3.Label :xyz    4. Label : ghi
  Textbox3 :        TextBox4 :

这些文本框文本属性中的每一个都应包含以其各自的标签名称结尾的文本对于TextBox1.text应该是xxxx.abcTextBox2.text应该是xxxx.def等等,如果不是,文本框应该有红色边框。

希望我清楚细节。那么我需要为每个文本框编写不同的ValidationRule吗?

任何你输入??

WPF 文本框的验证规则

为什么不有一个ValidationRule实现,其属性公开字段应该以什么结尾,例如:

public class EndsWithValidationRule : ValidationRule
{
    public string MustEndWith { get; set; }
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var str = value as string;
        if(str == null)
        {
            return new ValidationResult(false, "Please enter some text");
        }
        if(!str.EndsWith(MustEndWith))
        {
            return new ValidationResult(false, String.Format("Text must end with '{0}'", MustEndWith));
        }
        return new ValidationResult(true, null);
    }
}

然后你可以像这样使用它:

<TextBox x:Name="TextBox1">
    <TextBox.Text>
        <Binding Path="BoundProperty1" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:EndsWithValidationRule MustEndWith=".def" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
<TextBox x:Name="TextBox2">
    <TextBox.Text>
        <Binding Path="BoundProperty2" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:EndsWithValidationRule MustEndWith=".abc" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>