WPF Simple Validation Question - setting custom ErrorContent

后端 未结 2 1782
情话喂你
情话喂你 2021-01-02 01:28

If I have the following TextBox:



        
2条回答
  •  难免孤独
    2021-01-02 02:19

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

提交回复
热议问题