【问题标题】:IDataErrorInfo validation in DataGrid with CellTemplate and CellEditingTemplate使用 CellTemplate 和 CellEditingTemplate 在 DataGrid 中验证 IDataErrorInfo
【发布时间】:2012-09-15 19:50:51
【问题描述】:

我在 DataGrid 中的验证方面遇到问题。我在模型类中使用 IDataErrorInfo 验证。

问题出在具有单独 CellTemplate 和 CellEditingTemplate 的可编辑 DataGrid 中(注意是非空属性 - 如果为空或为空,验证将返回错误):

<!-- some other validated columns -->
<DataGridTemplateColumn Header="Note">
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>                                    
            <TextBox Name="textBoxNote" Text="{Binding Note, ValidatesOnDataErrors=True}" />                                    
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Note}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

在“保存”按钮上,我检查 MyObject.Error 验证属性,如果不为 null,我会显示一个 MessageBox。问题是,当将第一列(不是 Note 列)更改为有效值然后单击 Save 按钮时,.Error 属性为 null - 这是预期的(尽管不需要)行为,因为与 Note 属性上的 ValidatesOnDataError 绑定从未发生(TextBox 控件甚至从未存在过!)。但是,如果我在 TextBlock 上将 ValidatesOnDataErrors 设置为 true,那么我会在 DataGrid 中显示的每个对象(例如来自数据库)上得到不需要的验证,而我并不关心;在这种情况下,验证也可能需要很长时间...

处理此问题的正确方法是什么?我想在模型类中保留验证(对象应该知道它是否有效)。有没有办法在代码隐藏(保存按钮事件)中强制验证行绑定对象?或者我应该以某种方式初始化 .Error 对象构造?还有其他想法吗?

编辑: 如何将整行(所有单元格)置于编辑模式(CellEditingTemplate)?然后,所有的控件都将被加载和数据绑定,这也意味着验证...

谢谢大家, 数据库

【问题讨论】:

    标签: wpf validation datagrid idataerrorinfo celleditingtemplate


    【解决方案1】:

    好的,我设法重新验证了 IDataErrorInfo 对象 - 一种强制的 IDataErrorInfo 验证。否则我可以将新对象添加到 DataGrid,但属性(编辑的除外)从未得到验证。

    在我的所有模型对象(扩展 IDataErrorInfo)的超类中,我添加了这个方法:

    public virtual void Revalidate() // never needed to override though
    {
        Type type = this.GetType();
    
        // "touch" all of the properties of the object - this calls the indexer that checks
        // if property is valid and sets the object's Error property 
        foreach (PropertyInfo propertyInfo in type.GetProperties())
        {                
            var indexerProperty = this[propertyInfo.Name];
        }
    }
    

    现在,当用户将新对象添加到 DataGrid 时,我手动调用 myNewObject.Revalidate() 方法来设置我在将对象保存到数据库之前检查的 Error 属性。也许这不是最好的解决方案,但它对我来说非常轻松。

    感谢和问候, 数据库

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2013-04-29
      相关资源
      最近更新 更多