IDataErrorInfo/WPF Binding - Validation over many ViewModels - wpf

I'm trying to find an easy way to validate over a collection of ViewModels, using the IDataErrorInfo Interface.
I have a ListBox, which is bound to an ObservableCollection of ViewModels.
1 Class "DataView<VMUser>" with an ObservableCollection<VMUser>
1 ViewModel Class "VMUser"
If I implement the IDataErrorInfo into my ViewModel, i can validate for example if the Age > 21 and so on... But i cannot validate if there is no other user with the same email for example, because the ViewModels don't know anything from each other.
I didn't find a way to force the Bindings in my VMUser-DataTemplate to use the IDataErrorInfo of the DataView Class. (without clicking the OK-Button...)

For validation that is based on business rules, I usually expose a Validation Delegate that my ViewModel can set.
For example, the ViewModel containing your collection might look like this:
public ParentViewModel()
{
foreach(var user in UserCollection)
user.AddValidationErrorDelegate(ValidateUser);
}
private string ValidateUser(object sender, string propertyName)
{
if (propertyName == "Email")
{
var user = (UserVM)sender;
if (UserCollection.Count(p => p.Email== user.Email) > 1)
return "Another user already has this Email Address";
}
return null;
}
The idea is that your Model should only contain raw data, therefore it should only validate raw data. This can include validating things like maximum lengths, required fields, and allowed characters. Business Logic, which includes business rules, should be validated in the ViewModel, and this allows that to happen.
The actual implementation of my IDataErrorInfo on the UserVM class would look like this:
#region IDataErrorInfo & Validation Members
/// <summary>
/// List of Property Names that should be validated
/// </summary>
protected List<string> ValidatedProperties = new List<string>();
#region Validation Delegate
public delegate string ValidationErrorDelegate(object sender, string propertyName);
private List<ValidationErrorDelegate> _validationDelegates = new List<ValidationErrorDelegate>();
public void AddValidationErrorDelegate(ValidationErrorDelegate func)
{
_validationDelegates.Add(func);
}
#endregion // Validation Delegate
#region IDataErrorInfo for binding errors
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string propertyName]
{
get { return this.GetValidationError(propertyName); }
}
public string GetValidationError(string propertyName)
{
// If user specified properties to validate, check to see if this one exists in the list
if (ValidatedProperties.IndexOf(propertyName) < 0)
{
//Debug.Fail("Unexpected property being validated on " + this.GetType().ToString() + ": " + propertyName);
return null;
}
string s = null;
// If user specified a Validation method to use, Validate property
if (_validationDelegates.Count > 0)
{
foreach (ValidationErrorDelegate func in _validationDelegates)
{
s = func(this, propertyName);
if (s != null)
{
return s;
}
}
}
return s;
}
#endregion // IDataErrorInfo for binding errors
#region IsValid Property
public bool IsValid
{
get
{
return (GetValidationError() == null);
}
}
public string GetValidationError()
{
string error = null;
if (ValidatedProperties != null)
{
foreach (string s in ValidatedProperties)
{
error = GetValidationError(s);
if (error != null)
{
return error;
}
}
}
return error;
}
#endregion // IsValid Property
#endregion // IDataErrorInfo & Validation Members

Related

WinForms binding Generic List - checkable business object to a Grid

We all like how easy it is to bind with WPF. Now I am back working with Winforms and I am looking for a nice way to bind my grid to a List of Checkable of BusinessObject (I am sticking with BindingList for Winforms). So I am essentially just adding a checkable to my business object.
I am using a grid as there will be multiple columns where the user would edit (in this scenario Name and Description on the business object) - as well as adding new objects to the grid and removing from it. Checked list box does not fit for this purpose as I want to edit columns.
For this I am using .NET 4.
I basically want to reduce the amount of UI code in the scenario so I am using a view model based approach which will populate the list. I want the user to be able to check a box alongside each of the business object properties.
Sure I can use inheritance, but if I want to apply the same mechanism against a lot of business objects (having lots of different screens where you check items in a list for the different business objects). Maybe this would be the way to go - but I have my doubts.
Now depending upon the choice of grid - I am using Infragistics - the functionality would hopefully be pretty similar conceptually.
I thought about wrapping the business object up in a Checkable generic class:
using System;
using System.Collections.Generic;
public class Checkable<T> : ModelBase
{
public Checkable(T value)
{
_value = value;
}
private T _value;
public T Value
{
get
{
return _value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(_value, value))
{
_value = value;
OnPropertyChanged("Value");
}
}
}
private bool _checked;
public bool Checked
{
get { return _checked; }
set
{
if (_checked != value)
{
_checked = value;
OnPropertyChanged("Checked");
}
}
}
}
I have made up a business object for this scenario:
public class BusinessObject : ModelBase
{
public BusinessObject()
{
}
public BusinessObject(RepairType repairType)
{
_name = repairType.Name;
_id = repairType.Id;
}
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged("Name");
}
}
}
private string _description;
public string Description
{
get { return _description; }
set
{
if (description != value)
{
description = value;
OnPropertyChanged("Description");
}
}
}
private int _id;
public int Id
{
get { return _id; }
set
{
if (_id != value)
{
_id = value;
OnPropertyChanged("Id");
}
}
}
}
Where ModelBase just implements the INotifyPropertyChanged:
public abstract class ModelBase : INotifyPropertyChanged, IDisposable
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetProperty<T>(ref T field, T value, string propertyName = null)
{
if (object.Equals(field, value)) { return false; }
field = value;
OnPropertyChanged(propertyName);
return true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (disposing)
{
PropertyChanged = null;
}
}
}
So potentially for my grid datasource I would define:
// in view model
var datasource = new BindingList<Checkable<BusinessObject>>();
... populate list
grid.DataSource = viewmodel.DataSource;
So of course my scenario fails at the minute as Value is the BusinessObject reference which has the properties I want to bind to, and Checked is the property for a checkbox which I also want to bind to.
I am trying to kick start the old grey matter with some ideas on this. I don't really like writing code to define grid columns. However, the Infragistics grid has been ok for data binding directly to the BusinessObject at design time. Its possible to add an unbound column (checkbox for my scenario) and handle the checking/unchecking of items manually (which I might potentially have to do).
I am wondering if I am missing any neat tricks with Winform binding of late having missed out with Linq and Entity Framework when they appeared many years ago.

UI not calling INotifyDataErrorInfo.GetErrors()

I have a model implementing both INotifyPropertyChanged and INotifyDataErrorInfo. The Property changed event fires when ever I have a property modified, but for some reason when I raise the Error event handler, the UI does ever invoke the GetErrors method. This results in the validation error not being rendered to the UI.
Can someone take a look at how I have the INotifyDataErrorInfo set up and tell me if I'm doing something wrong?
Base model implementation
public class BaseChangeNotify : INotifyPropertyChanged, INotifyDataErrorInfo
{
private bool isDirty;
private Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();
public BaseChangeNotify()
{
}
public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public bool IsDirty
{
get
{
return this.isDirty;
}
set
{
this.isDirty = value;
this.OnPropertyChanged();
}
}
public bool HasErrors
{
get
{
return this.errors.Count(e => e.GetType() == typeof(ErrorMessage)) > 0;
}
}
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName) ||
!this.errors.ContainsKey(propertyName))
{
return null;
}
return this.errors[propertyName];/*.Where(e => (e is ErrorMessage));*/
}
protected virtual void AddError(string propertyName, string error, bool isWarning = false)
{
if (!this.errors.ContainsKey(propertyName))
{
this.errors[propertyName] = new List<string>();
}
if (!this.errors[propertyName].Contains(error))
{
if (isWarning)
{
this.errors[propertyName].Add(error);
}
else
{
this.errors[propertyName].Insert(0, error);
}
this.OnErrorsChanged(propertyName);
}
}
protected virtual void RemoveError(string propertyName, string error)
{
if (this.errors.ContainsKey(propertyName) &&
this.errors[propertyName].Contains(error))
{
this.errors[propertyName].Remove(error);
if (this.errors[propertyName].Count == 0)
{
this.errors.Remove(propertyName);
}
this.OnErrorsChanged(propertyName);
}
}
public virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
// Perform the IsDirty check so we don't get stuck in a infinite loop.
if (propertyName != "IsDirty")
{
this.IsDirty = true; // Each time a property value is changed, we set the dirty bool.
}
if (this.PropertyChanged != null)
{
// Invoke the event handlers attached by other objects.
try
{
// When unit testing, this will always be null.
if (Application.Current != null)
{
try
{
Application.Current.Dispatcher.Invoke(() =>
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
}
catch (Exception)
{
throw;
}
}
else
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
catch (Exception)
{
throw;
}
}
}
/// <summary>
/// Called when an error has changed for this instance.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
public virtual void OnErrorsChanged([CallerMemberName] string propertyName = "")
{
if (string.IsNullOrWhiteSpace(propertyName))
{
return;
}
if (this.ErrorsChanged != null)
{
this.ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}
}
Model using the implementation
public class PayItem : BaseChangeNotify
{
private Section section;
public Section Section
{
get
{
return this.section;
}
set
{
this.section = value;
this.ValidateSection();
this.OnPropertyChanged();
}
}
private void ValidateSection([CallerMemberName] string propertyName = "")
{
const string sectionError = "You must select a Section.";
if (this.Section == null || this.Section.Name.Length > 1)
{
this.AddError(propertyName, sectionError);
}
else
{
this.RemoveError(propertyName, sectionError);
}
}
The View trying to use it
<ComboBox Name="SectionComboBox"
ItemsSource="{Binding Path=ProjectSections}"
SelectedItem="{Binding Path=SelectedPayItem.Section,
NotifyOnValidationError=True,
UpdateSourceTrigger=PropertyChanged}">
The app is being wrote in WPF, and the WPF docs are pretty scarce. I've read through the Silverlight documentation on it along with a few other blog posts I found on the internet and have implemented in each of the different ways the blog authors suggest. Each time the result is the same, the GetErrors() method never gets hit by the Binding engine.
Can anyone see something that I'm doing wrong? When my model has its property set, I can step through the debugger and ultimately end up within the OnErrorsChanged event handler, and the event gets invoked. Nothing happens when it gets invoked though, so I'm stumped.
Thanks in advance for any help.
Johnathon
EDIT
Also I would like to note that I had been using IDataErrorInfo in the base class for the last couple of months without any issues. The binding worked, the errors were reported to the View and everything was happy. When I changed from IDataErrorInfo to INotifyDataErrorInfo, the validation appeared to stop communicating with the View.
The INotifyDataErrorInfo.HasErrors property must return true when raising the ErrorsChanged event. Otherwise the binding engine ignores the errors. Your HasErrors property will return false all the time. This happens because you are checking for items of type ErrorMessage but your dictionary contains items of type KeyValuePair<string, List<string>>. Besides that it is highly inefficent to count all the items. You should use .Any() instead.
By the way, the MSDN documentation of INotifyDataErrorInfo says the following:
Note that the binding engine never uses the HasErrors property,
although you can use it in custom error reporting.
This is plain wrong and it took me hours to find that out.

Business logic validation with Entity Framework and IDataErrorInfo

I'm working on a project using WPF and MVVM with Entity Framework 4.3, and I would like to know how can I perform business logic validation implementing the IDataErrorInfo interface.
All of my models (POCO classes) are implementing it in order to perform raw validations, like maxlength, non-negative numbers, and so on...
But what about bussiness logic validation, such as to prevent duplicate records?
Imagine I have a textbox for a material "reference", which must be unique, defined liked this:
<TextBox Text="{Binding Material.Reference, ValidatesOnDataErrors=True, NotifyOnValidationError=true,
UpdateSourceTrigger=PropertyChanged}">
The model will successfully validate the reference's length, but if there's already a material in my viewmodel's materials observablecollection, how should I notify the user of this fact from my ViewModel, yet taking advantage of the IDataErrorInfo messages?
I've done this in the past by exposing a validation delegate from my models that my ViewModels can hook into for additional business logic validation
The end result ends up looking like this:
public class MyViewModel
{
// Keeping these generic to reduce code here, but they
// should be full properties with PropertyChange notification
public ObservableCollection<MyModel> MyCollection { get; set; }
public MyModel SelectedModel { get; set; }
public MyViewModel()
{
MyCollection = DAL.GetAllModels();
// Add the validation delegate to each object
foreach(var model in MyCollection)
model.AddValidationErrorDelegate(ValidateModel);
}
// Validation Delegate to verify the object's name is unique
private string ValidateObject(object sender, string propertyName)
{
if (propertyName == "Name")
{
var obj = (MyModel)sender;
var existingCount = MyCollection.Count(p =>
p.Name == obj.Name && p.Id != obj.Id);
if (existingCount > 0)
return "This name has already been taken";
}
return null;
}
}
Most of my models inherit from a generic base class, which includes this validation delegate. Here's the relevant code from that base class, taken from my blog article on Validating Business Rules in MVVM
#region IDataErrorInfo & Validation Members
/// <summary>
/// List of Property Names that should be validated.
/// Usually populated by the Model's Constructor
/// </summary>
protected List<string> ValidatedProperties = new List<string>();
#region Validation Delegate
public delegate string ValidationErrorDelegate(
object sender, string propertyName);
private List<ValidationErrorDelegate> _validationDelegates = new List<ValidationErrorDelegate>();
public void AddValidationErrorDelegate(
ValidationErrorDelegate func)
{
_validationDelegates.Add(func);
}
#endregion // Validation Delegate
#region IDataErrorInfo for binding errors
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string propertyName]
{
get { return this.GetValidationError(propertyName); }
}
public string GetValidationError(string propertyName)
{
// Check to see if this property has any validation
if (ValidatedProperties.IndexOf(propertyName) >= 0)
{
string s = null;
foreach (var func in _validationDelegates)
{
s = func(this, propertyName);
if (s != null)
return s;
}
}
return s;
}
#endregion // IDataErrorInfo for binding errors
#region IsValid Property
public bool IsValid
{
get
{
return (GetValidationError() == null);
}
}
public string GetValidationError()
{
string error = null;
if (ValidatedProperties != null)
{
foreach (string s in ValidatedProperties)
{
error = GetValidationError(s);
if (error != null)
return error;
}
}
return error;
}
#endregion // IsValid Property
#endregion // IDataErrorInfo & Validation Members
This allows me to keep the basic data validation in my Models, and my ViewModels can attach any customized business logic validation they want to the Model as well.

Validation by comparing the properties of one entity against another

Here is what I have:
In the view there is a tab control with two tabs (sys1 and sys2) each with the same textboxes that are bound to the properties of their respective entities:
sys1:
<TextBox Text="{Binding sys1.Serial, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
sys2:
<TextBox Text="{Binding sys2.Serial, ValidatesOnExceptions=True, NotifyOnValidationError=True}" />
Using some form of validation I would like to compare the two values and display an error (red border is fine) if the values don't match.
I've used IDataErrorInfo before, but I'm not sure if this type of validation is possible.
Note: whether or not binding directly to the entity is "correct" is a discussion for another place and time. Just know that this is a team project and our teams standards are to bind to the entity so I can't change that unless I have a good reason. Perhaps if it's not possible validating when bound directly to the entity then I may have a good enough reason to change this.
Thanks
I usually expose a Validation Delegate from my Model that my ViewModel can use to attach business-rule validation to the Models.
For example, the ViewModel containing your objects might look like this:
public ParentViewModel()
{
sys1.AddValidationErrorDelegate(ValidateSerial);
sys2.AddValidationErrorDelegate(ValidateSerial);
}
private string ValidateSerial(object sender, string propertyName)
{
if (propertyName == "Serial")
{
if (sys1.Serial == sys2.Serial)
return "Serial already assigned";
}
return null;
}
The idea is that your Model should only contain raw data, therefore it should only validate raw data. This can include validating things like maximum lengths, required fields, and allowed characters. Business Logic, which includes business rules, should be validated in the ViewModel and this allows that to happen.
The actual implementation of my IDataErrorInfo on the Model class would look like this:
#region IDataErrorInfo & Validation Members
/// <summary>
/// List of Property Names that should be validated
/// </summary>
protected List<string> ValidatedProperties = new List<string>();
#region Validation Delegate
public delegate string ValidationErrorDelegate(object sender, string propertyName);
private List<ValidationErrorDelegate> _validationDelegates = new List<ValidationErrorDelegate>();
public void AddValidationErrorDelegate(ValidationErrorDelegate func)
{
_validationDelegates.Add(func);
}
#endregion // Validation Delegate
#region IDataErrorInfo for binding errors
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string propertyName]
{
get { return this.GetValidationError(propertyName); }
}
public string GetValidationError(string propertyName)
{
// If user specified properties to validate, check to see if this one exists in the list
if (ValidatedProperties.IndexOf(propertyName) < 0)
{
//Debug.Fail("Unexpected property being validated on " + this.GetType().ToString() + ": " + propertyName);
return null;
}
string s = null;
// If user specified a Validation method to use, Validate property
if (_validationDelegates.Count > 0)
{
foreach (ValidationErrorDelegate func in _validationDelegates)
{
s = func(this, propertyName);
if (s != null)
{
return s;
}
}
}
return s;
}
#endregion // IDataErrorInfo for binding errors
#region IsValid Property
public bool IsValid
{
get
{
return (GetValidationError() == null);
}
}
public string GetValidationError()
{
string error = null;
if (ValidatedProperties != null)
{
foreach (string s in ValidatedProperties)
{
error = GetValidationError(s);
if (error != null)
{
return error;
}
}
}
return error;
}
#endregion // IsValid Property
#endregion // IDataErrorInfo & Validation Members
P.S. I see nothing wrong with binding directly to the Model, especially in smaller applications. It may not be the "MVVM-purist" approach, however it is efficient and a lot less work, so I find it a perfectly valid option.
In the set (mutator) for sys1.Serial1 and sys2.Serial you should be able to get the other's value for a comparison.

Suggestions for Entity/Business object validation where the validation is dependent on other Entity/Service

Context
For a WPF application using the MVVM pattern I validate my entity(/business object) using the IDataErrorInfo interface on the entity so that validation rules in my entity are automatically called by WPF and the validationerrors automatically appear in the View. (inspired by Josh Smith in this article: http://joshsmithonwpf.wordpress.com/2008/11/14/using-a-viewmodel-to-provide-meaningful-validation-error-messages/
This works OK for simple validation rules like (name > 10 characters, value must be > 0)
But what to do when the validation rule in the model is more complex (like name must be unique / max value of the property is defined in another entity). I first thought of solving this by let the entity have a reference to a repository, but this doesn't feel good because I think there should only be references from the repository to the entity and not the other way (creating a cyclic reference)
Is it 'legal' to have a reference from the Recipe entity to the ConfigurationRepository. Or do you have a better suggestion?
Do you have suggestions how to implement Entity/Business object validation where the validation is dependent on other Entity/Service, like in the example below.
Below the simplified code of my real world problem.
In the Recipe entity I want to validate that the maximum temperature is less than the value stored in Configuration.MaximumTemperature. How would you solve this?
The Configuration entity (Stores the maximal allowed temperature for a recipe)
public class Configuration: INotifyPropertyChanged, IDataErrorInfo
{
private int _MaxTemperatureSetpoint;
public int MaxTemperatureSetpoint
{
get { return _MaxTemperatureSetpoint; }
set
{
if (value != _MaxTemperatureSetpoint)
{
_Setpoint = value;
RaisePropertyChanged("MaxTemperatureSetpoint");
}
}
}
The Simplified Recipe (Class where the user configures a recipe with a desired temperature (TemperatureSetpoint) and a desired Time (TimeMilliSeconds). The TemperatureSetpoint must be < Configuration.MaxTemperature)
public class Recipe: INotifyPropertyChanged, IDataErrorInfo
{
private int _TemperatureSetpoint;
public int TemperatureSetpoint
{
get { return _TemperatureSetpoint; }
set
{
if (value != _TemperatureSetpoint)
{
_Setpoint = value;
RaisePropertyChanged("Setpoint");
}
}
}
private int _TimeMilliSeconds;
public int TimeMilliSeconds
{
get { return _TimeMilliSeconds; }
set
{
if (value != _TimeMilliSeconds)
{
_TimeMilliSeconds= value;
RaisePropertyChanged("TimeMilliSeconds");
}
}
}
#region IDataErrorInfo Members
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string propertyName]
{
get
{
switch(propertyName)
{
case "TimeMilliSeconds":
//TimeMilliSeconds must be < 30 seconds
if (TimeMilliSeconds < 30000)
{ return "TimeMilliSeconds must be > 0 milliseconds";}
case "TemperatureSetpoint":
//MaxTemperatureSetpoint < maxTemperature stored in the ConfigurationRepository
int maxTemperatureSetpoint = ConfigurationRepository.GetConfiguration().MaxTemperatureSetpoint;
if (TemperatureSetpoint> maxTemperatureSetpoint )
{ return "TemperatureSetpoint must be < " + maxTemperatureSetpoint.ToString();}
}
}
#endregion
}
Recipe Repository
public interface IRecipeRepository
{
/// <summary>
/// Returns the Recipe with the specified key(s) or <code>null</code> when not found
/// </summary>
/// <param name="recipeId"></param>
/// <returns></returns>
TemperatureRecipe Get(int recipeId);
.. Create + Update + Delete methods
}
Configuration Repository
public interface IConfigurationRepository
{
void Configuration GetConfiguration();
}
For validation that is based on business rules, I usually expose a Validation Delegate that my ViewModel can set.
For example, the ViewModel for the Recipe might contain code that looks like this:
public GetRecipe(id)
{
CurrentRecipe = DAL.GetRecipe(id);
CurrentRecipe.AddValidationErrorDelegate(ValidateRecipe);
}
private string ValidateRecipe(string propertyName)
{
if (propertyName == "TemperatureSetpoint")
{
var maxTemp = Configuration.MaxTemperatureSetpoint;
if (CurrentRecipe.TemperatureSetpoint >= maxTemp )
{
return string.Format("Temperature cannot be greater than {0}", maxTemp);
}
}
return null;
}
The idea is that your Model should only contain raw data, therefore it should only validate raw data. This can include validating things like maximum lengths, required fields, and allowed characters. Business Logic, which includes business rules, should be validated in the ViewModel, and this allows that to happen.
The actual implementation of my IDataErrorInfo on the Recipe class would look like this:
#region IDataErrorInfo & Validation Members
/// <summary>
/// List of Property Names that should be validated
/// </summary>
protected List<string> ValidatedProperties = new List<string>();
#region Validation Delegate
public delegate string ValidationErrorDelegate(string propertyName);
private List<ValidationErrorDelegate> _validationDelegates = new List<ValidationErrorDelegate>();
public void AddValidationErrorDelegate(ValidationErrorDelegate func)
{
_validationDelegates.Add(func);
}
#endregion // Validation Delegate
#region IDataErrorInfo for binding errors
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string propertyName]
{
get { return this.GetValidationError(propertyName); }
}
public string GetValidationError(string propertyName)
{
// If user specified properties to validate, check to see if this one exists in the list
if (ValidatedProperties.IndexOf(propertyName) < 0)
{
//Debug.Fail("Unexpected property being validated on " + this.GetType().ToString() + ": " + propertyName);
return null;
}
string s = null;
// If user specified a Validation method to use, Validate property
if (_validationDelegates.Count > 0)
{
foreach (ValidationErrorDelegate func in _validationDelegates)
{
s = func(propertyName);
if (s != null)
{
return s;
}
}
}
return s;
}
#endregion // IDataErrorInfo for binding errors
#region IsValid Property
public bool IsValid
{
get
{
return (GetValidationError() == null);
}
}
public string GetValidationError()
{
string error = null;
if (ValidatedProperties != null)
{
foreach (string s in ValidatedProperties)
{
error = GetValidationError(s);
if (error != null)
{
return error;
}
}
}
return error;
}
#endregion // IsValid Property
#endregion // IDataErrorInfo & Validation Members
To be honest, I found that the baked in WPF validation methods are not complete and/or elegant enough. I find that using the WPF methods would scatter validation code and logic throughout my application and would even put some in my UI. Like you, I used Custom Business Objects (CBOs) for everything, and I was really wanting to keep my validation in my objects, since I was using them across several projects (a web service, UI, mobile, etc).
What I did was take my CBO (Recipe, in this case), and add some validation methods as properties. Eg:
public Func<string> NameValidation
{
get
{
return () =>
{
string result = null;
if (String.IsNullOrEmpty(Name)) result = "Name cannot be blank";
else if (Name.Length > 100) result = "Name cannot be longer than 100 characters";
return result;
};
}
}
After that, I decorated it with a custom attribute:
[AttributeUsage(AttributeTargets.Property)]
public class CustomValidationMethod : Attribute
{
}
then I created a Validate() method for object-level validation:
public override void Validate()
{
var a = GetType().GetProperties().Where(w => w.GetCustomAttributes(typeof(CustomValidationMethod), true).Length > 0);
foreach (var a2 in a)
{
var result = a2.GetValue(this, null) as Func<string>;
if (result != null)
{
var message = result();
if (message != null)
//There was an error, do something
else if (message == null && Errors.ContainsKey(a2.Name))
//There was no error
}
}
}
then I created custom controls that support my validation. In this case, it was a ComboBox that I derived from the standard ComboBox and added this code:
public Func<string> ValidationMethod
{
get { return (Func<string>) GetValue(ValidationMethodProperty); }
set { SetValue(ValidationMethodProperty, value); }
}
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (ValidationMethod != null && !String.IsNullOrEmpty(ValidationMethod()))
SetControlAsInvalid();
else
SetControlAsValid();
}
Once this is all set up, I can add field validation in the validation methods (which are stored in my CBOs instead of scattered throughout my code), I can add object-level validation in my Validate() method. As well, I can customize with ease how the control should behave with regards to validation.
To use this, in my VM I would call .Validate() first, then deal with any problems before saving. In my case specifically, I would store error messages in a collection and then query them (this also allowed me to store several error messages instead of the first one)

Resources