3
votes

If the binding engine cannot convert the entered text into the bound property's data type in a DataGridTextColumn (binding below), the cell gets a red border, and you cannot edit any other cells until the error is fixed. The border remains even if you tab out of the cell.

<DataGridTextColumn Binding="{Binding IntegerProperty, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True, ValidatesOnExceptions=True}" />

This is all great in my setup. The problem is that if I throw an exception in a property setter, the behavior is different. First the red border (validation error) is removed immediately when I tab out from the cell and I can continue to edit the rest of the grid's cells.

Is there any way to make the exception thrown in property setter behave similarly as the binding engine's way of handling FormatExceptions? The biggest annoyance is that the validation error is removed after moving out from the cell.

2

2 Answers

1
votes

I think you should NOT throw an exception in a property setter.

Take control of the validation by creating your own ValidationRules objects.

This might help you or you might be beyond this. http://www.wpfsharp.com/2012/02/03/how-to-disable-a-button-on-textbox-validationerrors-in-wpf/

When the exception is in the UI, the invalid value is not even passed through to the bound property.

Also, you can handle the exception instead of just throwing it and set the property to a default value or clear it out or something.

0
votes

There's nothing wrong with throwing an exception in a setter. After all, some setters call validation or other procedures while they're being set. For example, I may have a Connected property for a database that attempts to open a database connection when set to true. This could be set to a toggle button on my wpf window. That said, you could create a listener--something similar to this link: http://www.switchonthecode.com/tutorials/wpf-snippet-detecting-binding-errors.

In my case, I'm using MVVM and Prism/Unity framework. Once I retrieve the value and either trap an exception or raise one, I call an internal event within my View Model called NotifyViewOfException. I pass in the exception object and it handles it from there by displaying a window. You don't have to use Prism/Unity to do this. Based on your description, I don't know what you're using so I won't go into detail about that piece of it.