2012-09-24 86 views
0

我在DataGrid中验证时遇到了问题。我在模型类中使用IDataErrorInfo验证。使用CellTemplate和CellEditingTemplate在DataGrid中进行IDataErrorInfo验证

问题与独立CellTemplate和CellEditingTemplate可编辑的DataGrid(注意是不是空的属性 - 验证返回错误如果null或空):

<!-- 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。问题是,将第一列(不是注释一)更改为有效值,然后单击保存按钮时,.Error属性为空 - 这是预期的(虽然不需要)行为,因为与注释属性上的ValidatesOnDataError绑定从未发生(TextBox控件甚至从不存在!)。但是,如果我在TextBlock上将ValidatesOnDataErrors设置为true,那么我对DataGrid中显示的每个对象(比如说来自数据库)都会产生不需要的验证,我并不担心;在这种情况下验证也需要很多时间...

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

编辑: 我怎么能把整个行(所有细胞)进入编辑模式(CellEditingTemplate)?然后,所有的控件会被加载和数据绑定,这也意味着验证...

感谢所有, DB

回答

0

好吧,我设法重新验证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属性。也许这不是最好的解决方案,但它对我来说非常无痛。

感谢和问候, DB