Reputation: 15704
I have an issue with validation in WPF that I can't seem to resolve. I have a class (that implements IDataErrorInfo) that uses a property like-so.
private double? _SizeSearchValue;
public double? SizeSearchValue
{
get { return _SizeSearchValue; }
set
{
_SizeSearchValue = value;
NotifyChange("SizeSearchValue");
ValidateInputRow("SizeSearchValue");
}
}
It is bound to a textbox in XAML like this.
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="Size:"/>
<ComboBox Text="{Binding SizeSearchOption, ValidatesOnDataErrors=True}"/>
<TextBox Text="{Binding SizeSearchValue, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=False}"/>
</StackPanel>
The ValidateInputRow() function in the property setter will normally go through and run my custom validation routines and set errors appropriately so that the ComboBox and TextBox in the StackPanel mention above have a red border. Everything works just fine until I put a non-numeric string into the Textbox ("Abc" for example.)
With string input the binding runs its default validation, a FormatException is raised and the textbox gets its red border as per usual. My problem with this is that my custom validation routine will never run because the property setter in my class is never called.
I understand why this is happening, but I was wondering if anyone knew a way to catch an event, or the offending FormatException so that I can run my custom validation after the fact. I can't seem to figure this one out.
Upvotes: 1
Views: 939
Reputation: 15704
OK, Looks like I answered my own question. I looked further into the FormatException stack trace and found that an 'IValueConverter' is involved in the process so..... A solution is to use a converter like so:
<TextBox Text="{Binding SizeSearchValue, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource TestConverter}}"/>
In my case I just whipped one up (TestConverter) real quick and tied it up to my custom validation rules. Problem solved. I wonder if there are any equivalent solutions to the problem?
Upvotes: 1