我正在使用ValidationRule在我的数据网格中执行验证。我已将ValidationRules放在Row和DataGridTemplateColumn上。当用户与模板化列控件交互时,列验证工作正常,但行上的验证错误仍然存在,直到用户对任何列进行排序。
如果我可以在没有用户交互的情况下验证新行,我可能不需要在行和模板化列上进行验证。由于创建了一个新行并且所有控件都使用了数据模板,因此不会为列激活验证(如果我不使用行验证),那么为了验证新创建的行,我需要使用RowValidation,如下所述。 / p>
//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>