DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Data Engineering
  3. Data
  4. WPF 4.5 – Part 1 : Asynchronous Data Validation

WPF 4.5 – Part 1 : Asynchronous Data Validation

Jon Antoine user avatar by
Jon Antoine
·
Jul. 26, 12 · Interview
Like (0)
Save
Tweet
Share
6.90K Views

Join the DZone community and get the full member experience.

Join For Free

atlast here is the first post of a series about the new features of wpf 4.5 . validation of data is often if not always necessary in modern applications. from a long time, wpf provided the idataerrorinfo interfaces which permitted the automatic validation of your properties.

silverlight, with is asynchronous philosophy provided the inotifydataerrorinfo which performed the same thing but asyncrhonously.

it is a newinterface of wpf 4.5 and we will discover it in this post.

what’s inside ?

here is the definition of it:

as you can see there is only 3 things inside:

  • haserrors : a read-only boolean property which tells if the object as a whole have any validation errors;
  • geterrors : a method which returns validation errors for a given property;
  • errorschanged : an event which must be raised when new errors – or the lacks of errors – is detected. you have to raise this event for each property.

as a note, if you return false in the haserrors property, the binding will act as if there were no errors, even if they exists.

how to use it ?

with the traditionnal idataerrorinfo, you have to set to true the validatesondataerrors property on each binding to your object. there is nothing really new under the sun because this time you have to set the validatesonnotifydataerrors property to true .

in the linked demo project i create a form which display the properties of an object named ‘person’. here is how the validation with inotifydataerrorinfo is enabled in the binding:

<textbox text="{binding name,mode=twoway,validatesonnotifydataerrors=true}"/>

the binding will then register itself for the errorschanged event of the binded person. eeach time this event is raised for the binded property, the controls will dress itself to display an error. as pointed out before, this is done only if the haserrors is set to true.

i have implemented a delay in the validation of the person class. the validations occured after each set of any properties but it is delayed by ‘waitsecondsbeforevalidation’ seconds.

i also maintain a dictionary of all the errors by property name and use it to provide them via the geterros methods. the haserrors property returns true if this any error exists in this dictionary. here is the code for this basic implementation:

public system.collections.ienumerable geterrors(string propertyname)
{
    list<string> errorsforname;
    _errors.trygetvalue("name", out errorsforname);
    return errorsforname;
}
 
public bool haserrors
{
    get { return _errors.values.firstordefault(l => l.count > 0) != null; }
}
 
private dictionary<string, list<string>> _errors =
    new dictionary<string, list<string>>();
 
private void validate()
{
    task waittask = new task(() => thread.sleep(
        timespan.fromseconds(waitsecondsbeforevalidation)));
    waittask.continuewith((_) => realvalidation());
    waittask.start();
}
 
private object _lock = new object();
private void realvalidation()
{
    lock (_lock)
    {
        //validate name
        list<string> errorsforname;
        if (!_errors.trygetvalue("name", out errorsforname))
            errorsforname = new list<string>();
        else errorsforname.clear();
 
        if (string.isnullorempty(name))
            errorsforname.add("the name can't be null or empty.");
 
        _errors["name"] = errorsforname;
        if (errorsforname.count > 0) raiseerrorschanged("name");
 
        //validate age
        list<string> errorsforage;
        if (!_errors.trygetvalue("age", out errorsforage))
            errorsforage = new list<string>();
        else errorsforage.clear();
 
        if (age <= 0)
            errorsforage.add("the age must be greater than zero.");
 
        _errors["age"] = errorsforage;
        if (errorsforage.count > 0) raiseerrorschanged("age");
    }

finally, i have created a raiseerrorschanged method which ease the raising of validations event errors:

public event eventhandler<dataerrorschangedeventargs> errorschanged;
public void raiseerrorschanged(string propertyname)
{
    eventhandler<dataerrorschangedeventargs> handler = errorschanged;
    if (handler == null) return;
    var arg = new dataerrorschangedeventargs(propertyname);
    handler.invoke(this, arg);
}


demo application

the demo application can be found on this dropbox folder . don’t forget to register yourself on dropbox using this link :-) .

you can use the generate errors button to unvalidated the binded field and configure the delay to wait before the validation trough the interface:

Windows Presentation Foundation Data validation Property (programming) Data (computing)

Published at DZone with permission of Jon Antoine, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java Development Trends 2023
  • Using the PostgreSQL Pager With MariaDB Xpand
  • Kotlin Is More Fun Than Java And This Is a Big Deal
  • What Should You Know About Graph Database’s Scalability?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: