在我的应用程序中,我将“validatesonnotifydataerrors”与“DataAnnotations”一起使用,以便在用户编辑的字段为空或数据错误等时警告用户。我遇到的问题是,当显示我的 View 时,所有文本框都显示警告,因为它们是空的。我想做的只是在用户开始向该字段输入不正确的数据或者他们随后删除数据并且该字段变为空时显示警告。
这是我的一个文本框的 xaml:
<TextBox Text="{Binding Path=AttributeName, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=true}" />
这是后备属性:
private string _attributeName;
[StringLength(128)]
[Required(ErrorMessage = "Field cannot be blank")]
public string AttributeName
{
get { return _attributeName; }
set
{
_attributeName = value;
IsDirty = true;
OnPropertyChanged("AttributeName");
}
}
我想用这个框架做什么?
最佳答案
如果您希望文本框不立即显示验证,请删除;
[Required(ErrorMessage = "Field cannot be blank")]
然后改为包含一个 RegularExpression,如下所示;
[RegularExpression(@"^[a-zA-Z''-'\s]{1,128}$", ErrorMessage = "AttributeName must contain no more then 128 characters and contain no digits.")]
public string AttributeName
{
get { return _attributeName; }
set
{
_attributeName = value;
IsDirty = true;
OnPropertyChanged("AttributeName");
}
}
然后,在正则表达式中,您可以添加或删除某些方面,以便文本框不允许数字、符号等。
如您所见,您可以添加要包含的字符串范围,例如 {1,128}
(从 1 个字母到 128,之后它将在文本框中显示为红色) 所以理论上,您也不需要包含 [StringLength(128)]
。
看看This link有关数据注释/属性验证的更多信息。还要看看 This link also
希望这有帮助:)。
关于c# - 如何阻止 ValidatesOnNotifyDataErrors 过于活跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16584578/