Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>How I handle this in my view model classes:</p> <pre><code>public class MyViewModel : INotifyPropertyChanged, IDataErrorInfo { private Dictionary&lt;string, string&gt; _Errors = new Dictionary&lt;string, string&gt;(); public object SomeProperty { get { return _SomeProperty; } set { if (value != _SomeProperty &amp;&amp; !ValidationError("SomeProperty", value)) _SomeProperty = value; OnPropertyChanged("SomeProperty"); } } } private bool ValidationError(string propertyName, object value) { // I usually have a Dictionary&lt;string, Func&lt;object, string&gt;&gt; that maps property // names to validation functions; the functions return null if the property // is valid and an error message if not. You can embed the validation logic // in the property setters, of course, but breaking them out as separate methods // eases testing. _Errors[propertyName] = _ValidationMethods[propertyName](value); OnPropertyChanged("IsValid"); } public bool IsValid { get { return !(_Errors.Where(x =&gt; x.Value != null).Any())); } public string this[string propertyName] { get { return (_Errors.ContainsKey(propertyName)) ? _Errors[propertyName] : null; } } } </code></pre> <p>It's a little awkward to get this all set up at first, but once you've done it, you have a simple and straightforward way to report validation errors to the UI (via the <code>DataErrorValidationRule</code>), a straightforward way to know whether any given property is valid or not (check <code>_Errors</code>), and an <code>IsValid</code> property that tells you whether or not the whole view model is valid. (Also, you can extend the <code>IsValid</code> property to handle the case where all the properties of the view model are valid but the view model itself is not, e.g. two mutually exclusive flags are both set.) And as long as you make them <code>internal</code>, the validation methods can be unit tested via NUnit or whatever.</p> <p>I should add that the above code is off the top of my head and may or may not work as written - my actual working code is in a base class and has a lot of other things baked into it that would just be confusing.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload