Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception (validation) handling in WPF DataGrid

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.

like image 665
friskm Avatar asked May 28 '26 10:05

friskm


1 Answers

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.

like image 135
Rhyous Avatar answered Jun 01 '26 04:06

Rhyous