I have data validation in a 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
Here is the code:
XAML
<TextBox {...} Text="{Binding Path=ProductName,
UpdateSourceTrigger=PropertyChanged,
ValidatesOnDataErrors=True}"/>
On the ViewModel
, the validations are made with data annotations:
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.
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. During the data validation I return String.Empty
if the _firstLoad
is true. While setting your Property
ProductName
public string ProductName
{
get { return _productName; }
set
{
_productName = value;
_firstLoad = false;
SaveProduct.OnCanExecuteChanged();
OnPropertyChanged("ProductName");
}
}
I set the _firstLoad
to false. So now when the validation is triggered by PropertyChanged
event the validation will work as expected.
Validations will be checked whenever PropertyChanged
event gets raised for property.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With