ValidationRule for WPF Textbox

天涯浪子 提交于 2019-11-30 14:01:39

Why not have one ValidationRule implementation, with a property exposing what the field should end with, e.g:

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);

    }
}

Then you can use this like so:

<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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!