我不喜歡回答我的問題,但它似乎做到這一點的唯一方法是實現一個有效性規則,像什麼的下面(有可能是在它的一些錯誤):
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);
}
}
爲什麼不把自己的字符串放在MessageBox.Show();? – Terrance 2011-05-27 14:07:03
因爲我可能有很多其他的文本框,並且最好有一個驗證錯誤處理程序,它只是接收最新驗證錯誤的錯誤內容。 – 2011-05-27 14:09:30