加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – WPF简单验证问题 – 设置自定义的ErrorContent

发布时间:2020-12-15 06:36:17 所属栏目:百科 来源:网络整理
导读:如果我有以下TextBox: TextBox Height="30" Width="300" Margin="10" Text="{Binding IntProperty,NotifyOnValidationError=True}" Validation.Error="ContentPresenter_Error"/TextBox 而这在codebehind: private void ContentPresenter_Error(object sen
如果我有以下TextBox:
<TextBox Height="30" Width="300" Margin="10" Text="{Binding IntProperty,NotifyOnValidationError=True}" Validation.Error="ContentPresenter_Error">
</TextBox>

而这在codebehind:

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

如果在文本框中输入字母“x”,弹出的消息是

value ‘x’ could not be converted

有没有办法自定义这个消息?

解决方法

我不喜欢回答我自己的问题,但是看起来唯一的办法是实现一个ValidationRule,就像下面的(可能有一些bug):
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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读