WPF DataGrid验证 - 在单元格中显示工具提示

时间:2017-07-28 10:02:10

标签: c# wpf validation mvvm datagrid

我有一个看起来像这样的DataGrid:

<DataGrid ColumnWidth="45" CanUserAddRows="False" HeadersVisibility="None" ItemsSource="{Binding CorrectionMatrixA, Converter={StaticResource MatrixToDatatable}}">                        
   <DataGrid.RowValidationRules>
      <validators:MatrixValidationRule ValidationStep="UpdatedValue"/>
   </DataGrid.RowValidationRules>
</DataGrid>

在运行之前我对列没有任何了解 - 我的转换器将自定义对象转换为DataTable并将其绑定。当我无法使用

时,如何使用验证器显示输入错误
<DataGrid.Columns>

并在那里定义样式? 有没有解决方案?

修改

转换器:

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var casted = value as SimpleMatrix;
        if (casted == null)
            return Binding.DoNothing;

        var width = casted.width;
        var height = casted.height;

        var dataTable = new DataTable();

        for (var c = 0; c < width; c++)
        {
            dataTable.Columns.Add(new DataColumn());
        }

        int k = 0;
        for (int i = 0; i < height; i++)
        {
            var newRow = dataTable.NewRow();
            for (int j = 0; j < width; j++)
            {
                newRow[j] = casted.Fields.Single(a => a.X == i && a.Y == j).Value;
                k++;
            }
            dataTable.Rows.Add(newRow);
        }
        return dataTable.DefaultView;
    }

SimpleMatrix是我从XSD对象生成的。

验证:

    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        var group = (BindingGroup)value;
        foreach (var item in group.Items)
        {
            var row = ((DataRowView)item).Row;

            foreach (DataColumn column in row.Table.Columns)
            {
                var result = ValidateCell(column.ColumnName, row);
                if (result != ValidationResult.ValidResult)
                {
                    return result;
                }
            }
        }
        return ValidationResult.ValidResult;

    }

    private ValidationResult ValidateCell(string columnName, DataRow row)
    {

        DataTable table = row.Table;
        var column = table.Columns[columnName];
        object cellValue = row[column.ColumnName];

        if (string.IsNullOrEmpty(cellValue?.ToString()))
        {
            return new ValidationResult(false, "cell cannot be null");
        }

        if (column.DataType == typeof(string))
        {
            if (((string)cellValue).Any(c => !char.IsDigit(c) && c != ',' && c != '.'))
            {
                return new ValidationResult(false, "only digits and separator allowed");
            }
        }
        return ValidationResult.ValidResult;
    }

0 个答案:

没有答案