C1DataGrid for WPF使用技巧四:使用IDataErrorInfo校验

发布时间:2015/09/06 00:09 发布者:Alice

返回博客中心

使用IDataErrorInfo校验

IDataErrorInfo接口提供了校验数据和必要验证信息的能力,用户可以做接口绑定。

 

本文就让我们了解如何在C1DataGrid中使用IDataErrorInfo和校验数据。

C1DataGrid很容易的可以添加手动的行校验。这对于绑定到一个简单的集合来说,是非常有用的。

如下是一个简单的继承自IDataErrorInfode的类。

public class Person : IDataErrorInfo
 {
    private int age;
    private string name;

    public int Age
    {
       get { return age; }
       set { age = value; }
    }
    public string Name
    {
       get { return name; }
       set { name = value; }
    }
    public string Error
    {
       get
       {
          return null;
       }
    }
    public string this[string name]
    {
       get
       {
          string result = null;
          if (name == "Age")
          {
             if (this.age < 20 || this.age > 50)
             {
                   result = "Age must be less than 50 and greater than 20";
             }
          }
          if (name == "Name")
          {
             if (this.name.Length < 3)
                result = "Too Small Name";
          }
          return result;
       }
    }
 }

重要的一点就是在列绑定对象中设置ValidatesOnDataErrors 属性为true。

如下就是C1DataGrid在XAML在手动列种的定义。

<c1:C1DataGrid  x:Name="c1DataGrid1" AutoGenerateColumns="False">
 <c1:C1DataGrid.Columns>
 <c1:DataGridTextColumn Header="Name" Binding="{Binding Name,Mode=TwoWay,ValidatesOnDataErrors=True}"/>
 <c1:DataGridNumericColumn Header="Age" Binding="{Binding Age,Mode=TwoWay,ValidatesOnDataErrors=True}"/>
 </c1:C1DataGrid.Columns>
 </c1:C1DataGrid>

我们在C1DataGrid的'CommittingEdit'事件中,手动的添加行校验的结果。

c1DataGrid1.CommittingEdit += (s, e) =>
 {
    if (Validation.GetHasError(e.EditingElement))
    {
       var ve = Validation.GetErrors(e.EditingElement);
       e.Row.ValidationResults.Add(new System.ComponentModel.DataAnnotations.ValidationResult((ve[0]).ErrorContent.ToString(), new string[] { e.Column.Name }));
    }
    else
    {
       foreach (var result in e.Row.ValidationResults)
       {
          if (result.MemberNames.First() == e.Column.Name)
          {
             e.Row.ValidationResults.Remove(result);
             break;
          }
       }
    }
 };

本文所讨论的内容,源代码如下所示:

 WpfDataGridIDataErrorInfo.zip (17.81 kb)

 


C1DataGrid的在线英文产品文档地址:

http://helpcentral.componentone.com/nethelp/C1datagridWPF/

如果你对C1DataGrid感兴趣,请到我们的官网下载最新版本:/download/?pid=6

如果你有疑问,可以到GCDN论坛获得技术支持:http://gcdn.grapecity.com.cn/showforum-138.html

 

C1DataGrid for WPF使用技巧》系列文章

(一)在表头展示合计信息

(二)简单数据绑定

(三)C1DataGrid的条件话数据模板


关于葡萄城

赋能开发者!葡萄城是专业的集开发工具、商业智能解决方案、低代码开发平台于一身的软件和服务提供商,为超过 75% 的全球财富 500 强企业提供服务。葡萄城专注控件软件领域30年,希望通过模块化的开发控件、灵活的低代码应用开发平台等一系列开发工具、解决方案和服务,帮助开发者快速响应复杂多变的业务需求,最大程度地发挥开发者的才智和潜能,让开发者的 IT 人生更从容更美好。

了解详情,请访问葡萄城官网