WPF文本框的ValidationRule

Pat*_*til 7 c# wpf textbox validationrule

我是WPF的新手.在我的UserControl中,我有8个标签及其各自的8个文本框,如下所示:

1.Label : abc   2.Label : def
  TextBox1 :        TextBox2 :

3.Label :xyz    4. Label : ghi
  Textbox3 :        TextBox4 :
Run Code Online (Sandbox Code Playgroud)

每个文本框的文本属性应包含文本与其相应的标签名称为结局TextBox1.text应该是xxxx.abc,TextBox2.text应该是xxxx.def等.如果没有文本框应该有红色边框.

希望我清楚细节.所以我需要ValidationRule为每个文本框写不同的??

你输入的任何??

Luk*_*oid 27

为什么没有一个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);

    }
}
Run Code Online (Sandbox Code Playgroud)

然后你就可以这样使用:

<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>
Run Code Online (Sandbox Code Playgroud)