DataGrid control implements validation

The DataGrid control enables you to perform validation at the cell and row level. When using cell-level validation, you can validate individual properties of the bound data object when the user updates the value. With row-level validation, when a user commits changes to a row, the entire data object can be validated. You can also provide custom visual feedback for validation errors, or use the default visual feedback provided by the DataGrid control .

  1. Validate a single cell value

Specifies one or more validation rules on the binding to be used with the column. This is similar to validating data in a simple control, as described in Data Binding Overview .

The following example demonstrates a DataGrid control with four columns of different properties bound to a business object. The three-column ExceptionValidationRule is specified by setting the ValidatesOnExceptions property to true.

If the user enters an invalid value (such as a non-integer in the Course ID column), a red border appears around the cell.

This default validation feedback can be changed as described in the following procedure.

  1. Validate multiple values ​​in a single row

Implement a ValidationRule subclass that checks several properties of the bound data object. In the Validate method implementation, cast the valueparameter value to a BindingGroup instance. Then, you can access the data object through the property Items .

The following example demonstrates this process to verify that an StartDateobject 's property value is Courseearlier than its EndDateproperty value.

 

Add validation rules to the DataGrid.RowValidationRules collection. The RowValidationRules property provides direct access to the properties of the ValidationRules instance's BindingGroup , which groups all bindings used by the control.

The following example RowValidationRules sets properties in XAML. The ValidationStep property is set to UpdatedValue to only validate after updating the bound data object.

 

Guess you like

Origin blog.csdn.net/weixin_44591600/article/details/123111791