gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:42:41 27 4
gpt4 key购买 nike

如果我有以下文本框:

<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”,弹出的信息是

value 'x' could not be converted

有没有办法自定义此消息?

最佳答案

我不喜欢回答我自己的问题,但看起来唯一的方法是实现一个 ValidationRule,如下所示(其中可能有一些错误):

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

关于c# - WPF 简单验证问题 - 设置自定义 ErrorContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6153302/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com