简体   繁体   中英

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.

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";

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM