i would like to implement the validation mechanism which simulates Errorprovider in winforms. i tried to use IDataErrorInfo but the problem is it is trying to perform validation on the form load. my requirement is i need to perform validation on click of a button in the page. Is there any other better approach to perform validation in WPF?
Sounds like you have validation figured out now it the easy part - prevent it from validating until needed.. Put a bool property on the class that implements IErrorInfo:
public bool IsReadyToValidate {get;set;}
in each property
public object SomeProperty
{
get {return _someProperty;}
set
{
if(_someProperty == value) return;
_property = value;
if(IsReadyToValidate)
//do validation
or if you use attribute based validation:
[CustomMethodValidator("ValidateSomeProperty")]
public string SomeProperty
{
if(_someProperty == value) return;
set
{
if(_property == value)
return;
_property = value;
RaisePropertyChanged(() => SomeProperty);
}
}
private bool ValidateSomeProperty()
{
bool isValid = true;
if(IsReadyToValidate)
//do validation
return is valid;
On the click of your button, set the IsReadyToValidate to true and revalidate. Again it all depends on your implementations. Put maybe a method like this?
public void Validate()
{
foreach (var prop in PropertiesWithValidators[GetType()])
ValidateProperty(prop.Name);
HasErrors = _errorDictionary.Count > 0;
RaisePropertyChanged(() => Error);
}
or you could do some brute way, like restuffing the properties after you flipped the flag to validate
public void Validate()
{
IsReadyToValidate = true;
//now it will validate:
SomeProperty = SomeProperty;
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.