WPF简单的验证问题 - 设置自定义ErrorContent [英] WPF Simple Validation Question - setting custom ErrorContent

查看:184
本文介绍了WPF简单的验证问题 - 设置自定义ErrorContent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有下面的文本框:

If I have the following TextBox:

<TextBox Height="30" Width="300" Margin="10" Text="{Binding IntProperty, 
       NotifyOnValidationError=True}" Validation.Error="ContentPresenter_Error">
</TextBox>

这在代码隐藏:

private void ContentPresenter_Error(object sender, ValidationErrorEventArgs e) {
   MessageBox.Show(e.Error.ErrorContent.ToString());
}

如果我输入在文本框中输入字母X的消息,弹出是

If I enter the letter "x" in the text box, the message that pops up is

值'X'不能转换

有没有一种方法来定制这个消息?

Is there a way to customize this message?

推荐答案

我不喜欢回答我的问题,但它似乎要做到这一点的唯一方法是实现一个有效性规则,像什么是下面(有可能是它的一些错误):

I dislike answering my own question, but it appears the only way to do this is to implement a ValidationRule, like what's below (there may be some bugs in it):

public class BasicIntegerValidator : ValidationRule {       

    public string PropertyNameToDisplay { get; set; }
    public bool Nullable { get; set; }
    public bool AllowNegative { get; set; }

    string PropertyNameHelper { get { return PropertyNameToDisplay == null ? string.Empty : " for " + PropertyNameToDisplay; } }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
        string textEntered = (string)value;
        int intOutput;
        double junkd;

        if (String.IsNullOrEmpty(textEntered))
            return Nullable ? new ValidationResult(true, null) : new ValidationResult(false, getMsgDisplay("Please enter a value"));

        if (!Int32.TryParse(textEntered, out intOutput))
            if (Double.TryParse(textEntered, out junkd))
                return new ValidationResult(false, getMsgDisplay("Please enter a whole number (no decimals)"));
            else
                return new ValidationResult(false, getMsgDisplay("Please enter a whole number"));
        else if (intOutput < 0 && !AllowNegative)
            return new ValidationResult(false, getNegativeNumberError());

        return new ValidationResult(true, null);
    }

    private string getNegativeNumberError() {
        return PropertyNameToDisplay == null ? "This property must be a positive, whole number" : PropertyNameToDisplay + " must be a positive, whole number";
    }

    private string getMsgDisplay(string messageBase) {
        return String.Format("{0}{1}", messageBase, PropertyNameHelper);
    }
}

这篇关于WPF简单的验证问题 - 设置自定义ErrorContent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆