[英]How to stop the validation trigger to start automatically in wpf
I have data validation in a ViewModel
. 我在
ViewModel
中进行了数据验证。 When I load the View
, the validation is checked without changing the content of the TextBox
, meaning by loading the view the error styles are set to TextBox
当我加载
View
,检查验证而不更改TextBox
的内容,这意味着通过加载视图将错误样式设置为TextBox
Here is the code: 这是代码:
XAML
<TextBox {...} Text="{Binding Path=ProductName,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"/>
On the ViewModel
, the validations are made with data annotations: 在
ViewModel
,使用数据注释进行验证:
Code
private string _productName;
[Required(AllowEmptyStrings = false, ErrorMessage = "The Product Name can't be null or empty.")]
[StringLength(50, ErrorMessage = "The Product Name can't be longer than 50.")]
[Uniqueness(Entities.Product, ErrorMessage = "A Product with that Name already exists ")]
public string ProductName
{
get { return _productName; }
set
{
_productName = value;
SaveProduct.OnCanExecuteChanged();
OnPropertyChanged("ProductName");
}
}
How can I stop the validation triggering when the view loads? 如何加载视图时如何停止验证触发?
I don't want the TextBox
to show an error until data is inserted. 在插入数据之前,我不希望
TextBox
显示错误。
Validations will be checked whenever PropertyChanged
event gets raised for property. 每当为属性引发
PropertyChanged
事件时,都将检查验证。
I suspect from constructor you are setting property . 我怀疑你是在构造函数中设置属性 。 Instead at load, consider setting back up field of your property and not actual property.
而是在加载时,考虑设置属性的备份字段而不是实际属性。
_productName = "TestName";
Even I had the same problem. 即使我有同样的问题。 Fixed it by using a simple trick.
通过使用一个简单的技巧修复它。 I defined a private boolean
我定义了一个私有布尔值
private bool _firstLoad;
In the constructor I set the _firstLoad
to true. 在构造函数中,我将
_firstLoad
设置为true。 During the data validation I return String.Empty
if the _firstLoad
is true. 在数据验证期间,如果
_firstLoad
为true,则返回String.Empty
。 While setting your Property
ProductName
在设置
Property
ProductName
public string ProductName
{
get { return _productName; }
set
{
_productName = value;
_firstLoad = false;
SaveProduct.OnCanExecuteChanged();
OnPropertyChanged("ProductName");
}
}
I set the _firstLoad
to false. 我将
_firstLoad
设置为false。 So now when the validation is triggered by PropertyChanged
event the validation will work as expected. 所以现在当
PropertyChanged
事件触发验证时,验证将按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.