微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如果我有以下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);
    }
}

原文地址:https://www.jb51.cc/csharp/95137.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐