Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the validation trigger to start automatically in wpf

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.

like image 646
aledustet Avatar asked Jan 05 '14 17:01

aledustet


2 Answers

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.

like image 133
Sandesh Avatar answered Nov 07 '22 09:11

Sandesh


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";
like image 33
Rohit Vats Avatar answered Nov 07 '22 08:11

Rohit Vats