I'd like to know if it is possible to customize the ErrorContent
property which can be accessed through the Validation.Errors
collection when there is an exception validation problem.
As an example, suppose you have a source property of type int
that is data-bound to the TextBox.Text
property. If the user types a non-integer value into that TextBox
, then an exception occurs, and the Validation.Errors
collection will have an entry that contains an error message like this:
I want to know if I can determine when an exception problem occurs and choose a new message, such as
"Please enter a positive integer specifying the number of digits (must be between 2 and 10)."
I do not believe the IDataErrorInfo
interface will suffice in providing the information I want. This is because I have no way of returning an error message when there is an exception problem.
For those interested, I've implemented IDataErrorInfo
similar as below:
string IDataErrorInfo.Error { get { return null; } }
string IDataErrorInfo.this[string property]
{
get
{
string message = null;
switch (property) {
case "Digits":
if (Digits < 2 || Digits > 10)
message = "There must be between 2 and 10 digits.";
break
}
return message;
}
}
In this instance, Digits
is the int
source property. In this implementation I have no way of obtaining the text input from the user (and thus cannot check if it can cast to an int
). Simply, I can only specify an error message for when there are no exception problems (if the user types an out of range integer, the IDataErrorInfo message appears).
So, how can I tell WPF to use the quoted error message when there is a validation exception? According to MSDN, the Validation.Errors
collection cannot be modified by the application (although that is what IDataErrorInfo
does).
The XAML style for the
TextBox
in the above image follows:
<Style x:Key="ValidatedTextBoxStyle" TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>