Tuesday, August 9, 2011

WPF and Silverlight Validation using IDataErrorInfo

How to validate WPF or Silverlight Form or Page..?
Validations in wpf
There are several ways to validate a WPF or Silverlight form and IDataError Info is the one of the interesting way to do validations.

IDataErrorInfo is a part of System.dll Assembly.

this interface contains couple of properties which we have to override in our implementation.

1) string Error { get; }

2) string this[string columnName] { get; }

out of these two properties the second property is an Index.
(you can learn more about indexers here: http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx)

Here is a sample which will give some information about the implementation of IDataErrorInfo.

Here I am creating a user Class which implements IDataErrorInfo.



public class User : ViewModelbase, IDataErrorInfo
{
private string firstName;

public string FirstName
{
get { return firstName; }
set { firstName = value;
OnPropertyChanged("FirstName");
}
}

private string lastName;

public string LastName
{
get { return lastName; }
set
{
lastName = value;
OnPropertyChanged("LastName");
}
}


#region IDataErrorInfo Members

public string Error
{
get { throw new NotImplementedException(); }
}

public string this[string columnName]
{
get
{
string result = null;
if (columnName == "FirstName")
{
if (string.IsNullOrEmpty(FirstName))
result = "Please enter a First Name";
}
if (columnName == "LastName")
{
if (string.IsNullOrEmpty(LastName))
result = "Please enter a Last Name";
}

return result;
}
}

#endregion

}


You can observe the public string this[string columnName] property which contains if condition for Firstname and lastname.. when ever we there is a property changed notification then this indexer will get initiated and checks for the valid value and the value it returned will appear as error message.

Implementing the following style will give error template to a text box whenever validation returns error message

No comments:

Post a Comment