tags:

views:

527

answers:

2

My current setup binds the Text property of my TextBox to a certain Uri object. I'd love to use WPF's inbuilt validation to detect invalid URIs, and proceed from there. But this doesn't seem to be working?

I would imagine that it would throw an exception if I entered, e.g., "aaaa" as a URI. Thus, triggering my current setup, which is supposed to detect exceptions like so:

<TextBox Grid.Column="1" Name="txtHouseListFile" DockPanel.Dock="Right" Margin="3">
 <TextBox.Text>
  <Binding Source="{StaticResource Settings}" Path="Default.HouseListFile" Mode="TwoWay">
   <Binding.ValidationRules>
    <ExceptionValidationRule />
   </Binding.ValidationRules>
  </Binding> 
 </TextBox.Text>
</TextBox>

Then I would imagine I could check the various Validation properties, like so?

Validation.GetHasError(this.txtHouseListFile)

But, this appears to not work. Maybe it doesn't throw exceptions when trying to convert? Or maybe my setup's wrong? Corrections to either would be great.

+1  A: 

You can try create our own ValidationRule (inherit from ValidationRule). In this class, override Validate(...) and try create an URI object and catch the exceptions. In the catch, just set the e.Message to exception message.

(I am not too sure what is your binding source. Is it a URI object or a string?)

decasteljau
My binding source is a Uri object, not a string.So can you confirm that there's no way to use the built-in ExceptionValidationRule? It seems like it should throw a UriFormatException when attempting to initialize the Uri from an invalid string... and thus trigger the rule.
Domenic
A: 

OK, I think I know what is going on. The binding doesn't know how to convert a string to a URI object (because the textbox Text property is a string). You need a converter to help him.

Try this: Create a converter class (inherit from IValueConverter) that:

  • convert a string to a Uri using the Uri constructor
  • convert a Uri to a string (using one of the multiple getters)

Put your converter in the Binding. Then, the converver will throw an exception in the Uri constructor and your ExceptionValidationRule will catch it.

Look here to know how to use a converter.

decasteljau
That seems pretty sensible. I'll test it sometime this weekend, and if it's true I'll mark the answer as accepted :). Many thanks!
Domenic
This does not appear to work (sorry for the huge delay). The exception is never caught.
Domenic