The IDataErrorInfo
interface exposes a property named Error
. This is the property that contains the textual error message that you set in the indexer that you have to implement as part of the interface.
Please note that this interface will only show one error message at a time without user customisation. It is difficult to give you an accurate example because you didn't tell us any details of your class that implements this interface. However, it goes a bit like this:
Your indexer:
public override string this[string propertyName]
{
if (propertyName = "Name" && Name == string.Empty) return "Please add the name";
return string.Empty;
}
When the interface sees a change to a property, it calls this indexer. If the name of the property is found in here with an error message, that message is set in the Error
property of the data class that implements the interface. Therefore, to see the message, you simply Bind
to the Error
property:
<TextBlock Text="{Binding Error}" Foreground="Red" />
<TextBlock Text="{Binding Name}" />
(Of course, the colour is optional).
UPDATE >>>
The IDataErrorInfo
interface is implemented by the model/data type class(es). Therefore, the Error
property is in the data type class (as you have shown in your code) and you can access it in just the same way that you would access any other property from that class:
clsDamagedProducts instance = new clsDamagedProducts();
instance.UnitName = "Some Name";
MessageBox.Show(instance.Error);
UPDATE 2 >>>
There are many ways to get these validation errors. One way is to simply pass each property name that you want to validate to the indexer method and return the result:
public string Error
{
get
{
if (this["Name"] != string.Empty) return this["Name"];
...
else if (this["OtherProperty"] != string.Empty) return this["OtherProperty"];
return string.Empty;
}
}
You mentioned the Validation.Errors
property, which you can also use, but in order to do that, you need to set the ValidatesOnDataErrors
and/or the NotifyOnValidationError
properties to True
. Please refer to the WPF: Validation made easy with IDataErrorInfo and WPF Validation with Attributes and IDataErrorInfo interface in MVVM articles for more information on these.
I personally prefer not to use those properties, or the Error
property directly. Instead, I have an abstract
collection property named Errors
in my base class which is overridden in derived classes:
public override ObservableCollection<string> Errors
{
get
{
errors = new ObservableCollection<string>();
errors.AddUniqueIfNotEmpty(this["Name"]);
errors.AddUniqueIfNotEmpty(this["EmailAddresses"]);
errors.AddUniqueIfNotEmpty(this["StatementPrefixes"]);
return errors;
}
}
As you can see... this enables me to view multiple errors at once.