即使无效,验证也会成功

时间:2017-11-06 08:53:11

标签: c# wpf validation datagrid

我使用以下代码,在保存之前检查错误,但是' IsValid'即使出现错误,也始终评估为真。

<DataGrid.RowValidationErrorTemplate>
     <ControlTemplate>
            <Grid  Margin="0,-2,0,-2" ToolTip="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, Path=(Validation.Errors)[0].ErrorContent}">
                  <Ellipse StrokeThickness="0" Fill="Red" Width="{TemplateBinding FontSize}" Height="{TemplateBinding FontSize}" />
                      <TextBlock Text="!" FontSize="{TemplateBinding FontSize}" FontWeight="Bold" Foreground="White" HorizontalAlignment="Center"  />
                </Grid>
            </ControlTemplate>
        </DataGrid.RowValidationErrorTemplate>
    <DataGrid.RowValidationRules>
         <local:OrderItemValidationRule ValidationStep="UpdatedValue"/>
    </DataGrid.RowValidationRules>


OrderItemValidationRule rule = new OrderItemValidationRule();
foreach (DataGridRow dgr in orderItemDataGrid.GetDataGridRows())
{
   ValidationResult res = rule.Validate(dgr.BindingGroup, null);
   if (!res.IsValid)
   {
      MessageBox.Show("Cannot save, there are errors in the ORDER ITEMS.", "Error Message", MessageBoxButton.OK, MessageBoxImage.Error);
      dgr.BringIntoView();
      return false;
    }
}

验证规则:

public class OrderItemValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            OrderItem order = (value as BindingGroup).Items[0] as OrderItem;
            if (order.ProductID==0 && order.Product==null)
            {
                return new ValidationResult(false,"Please enter PRODUCT.");
            }
            if (order.Quantity==0)
            {
                return new ValidationResult(false, "Please enter QUANTITY.");
            }

             return ValidationResult.ValidResult;
        }
    }

1 个答案:

答案 0 :(得分:0)

GetDataGridRows()做什么?这对我来说很好用:

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    OrderItemValidationRule rule = new OrderItemValidationRule();
    foreach (object item in orderItemDataGrid.Items)
    {
        DataGridRow dgr = orderItemDataGrid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (dgr != null)
        {
            ValidationResult res = rule.Validate(dgr.BindingGroup, null);
            if (!res.IsValid)
            {
                MessageBox.Show("Cannot save, there are errors in the ORDER ITEMS.", "Error Message", MessageBoxButton.OK, MessageBoxImage.Error);
                dgr.BringIntoView();
            }
        }
    }
}