绑定到动态数据表的datagrid的单元验证

时间:2015-03-04 13:00:19

标签: c# wpf datagrid wpfdatagrid

我绑定了数据表格的数据网格。在运行时期间确定列数。我在编辑后使用Datagrid.RowValidationRule来验证单元格的内容。如果出错,则使用样式突出显示带红色边框的行。

是否可以仅突出显示具有红色边框的无效数据的单元格,而不是突出显示完整的行?

结合:

 ItemsSource="{Binding Path=., ValidatesOnExceptions=True, NotifyOnValidationError=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" 
                                  AutoGenerateColumns="True"

验证:

<DataGrid.RowValidationRules>
                                <local:RowDataValidationRule ValidationStep="UpdatedValue" ValidatesOnTargetUpdated="True"/>
                            </DataGrid.RowValidationRules>

风格:

 <Style x:Key="RowStyle" TargetType="{x:Type DataGridRow}">
        <Style.Triggers>
            <Trigger Property="Validation.HasError" Value="true">
                <Setter Property="BorderThickness" Value="2"/>
                <Setter Property="BorderBrush" Value="Red"/>
                <Setter Property="ToolTip"
   Value="{Binding RelativeSource={RelativeSource Self},
       Path=(Validation.Errors)[0].ErrorContent}"/>
            </Trigger>
        </Style.Triggers>
    </Style>

代码隐藏:

public class RowDataValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {

        BindingGroup group = (BindingGroup)value;

        StringBuilder error = null;
        foreach (var item in group.Items)
        {
            DataRowView rowView = item as DataRowView;
            if (rowView != null)
            {
               // Validation logic, sets error
            }
        }
        if (error != null)
            return new ValidationResult(false, error.ToString());
        return ValidationResult.ValidResult;
    }

}

1 个答案:

答案 0 :(得分:1)

当然,您可以为每列指定一个或多个验证规则。 假设您有一个绑定到“描述”DataColumn的TextBox网格列。 因此,您可以通过这种方式定义DataGridTextColumn(查看“绑定”节点)

<DataGridTextColumn Header="Description">
    <DataGridTextColumn.Binding>
        <Binding Path="[Description]">
            <Binding.ValidationRules>
                <local:MyValidationRule />
            </Binding.ValidationRules>
        </Binding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

修改

当然,你也可以使用代码来做同样的事情。 您只需要向DataGrid添加一个事件处理程序:

<DataGrid AutoGenerateColumns="True" AutoGeneratingColumn="DataGrid_AutoGeneratingColumn" />

然后,您将以这种方式将验证规则添加到Binding:

private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    Binding binding;
    DataGridTextColumn dataGridTextColumn = e.Column as DataGridTextColumn;
    if(dataGridTextColumn != null)
    {
        binding = new Binding(String.Concat("[", dataGridTextColumn.Header, "]"));
        binding.Mode = BindingMode.TwoWay;
        binding.ValidationRules.Add(new MyValidationRule());

        dataGridTextColumn.Binding = binding;
    }
}

当然,您必须添加逻辑以考虑其他DataGrid列类型。