问题描述:

I am using ValidationRule to perform validations in my datagrid. I have put ValidationRules on both the Row as well as the DataGridTemplateColumn. The column validation works fine when user interacts with the Templated column control but the validation errors on the Row remain until user sorts any of the column.

I may not need the validations on both the row and Templated column if I can validate the new row without the user interaction. Since a new row is created and all controls are using Data Templates, the validations dont fire for the columns (if I dont use Row Validation), So in order to validate the newly created row, I need to use RowValidation as described below.

//CustomValidation class

public class CustomValidation : ValidationRule

{

public override ValidationResult Validate(object value, CultureInfo cultureInfo)

{

MyClass myClassObj = null;

if ((value as BindingGroup) == null)

{

if (value as System.Windows.Data.BindingExpression != null)

{

myClassObj = ((System.Windows.Data.BindingExpression)(value)).DataItem as MyClass;

}

else

{

myClassObj = value as MyClass;

}

}

else

{

if ((value as BindingGroup).Items.Count > 0)

{

myClassObj = (value as BindingGroup).Items[0] as MyClass;

}

}

//Perform Validation here

return ValidationResult.ValidResult;

}

}

//DataGrid Row Validation Rule

<DataGrid.RowValidationRules>

<validation:CustomValidation ValidationStep="UpdatedValue" ValidatesOnTargetUpdated="True" />

</DataGrid.RowValidationRules>

//DataGrid Custom Column

<DataGridTemplateColumn Width="120" Header="Custom Checkbox" HeaderStyle="{StaticResource StyleColumnHeader}" CellStyle="{StaticResource StyleDataGridCell}">

<DataGridTemplateColumn.CellTemplate>

<DataTemplate>

<CheckBox HorizontalContentAlignment="Center" Width="20">

<CheckBox.IsChecked>

<Binding Path="CustomCheckboxValue" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" ValidatesOnExceptions="True" NotifyOnValidationError="True" NotifyOnTargetUpdated="True" NotifyOnSourceUpdated="True">

<Binding.ValidationRules>

<validation:CustomValidation ValidationStep="UpdatedValue" />

</Binding.ValidationRules>

</Binding>

</CheckBox.IsChecked>

</CheckBox>

</DataTemplate>

</DataGridTemplateColumn.CellTemplate>

相关阅读:
Top