【问题标题】:WPF DataGrid validate duplicate itemsWPF DataGrid 验证重复项
【发布时间】:2015-10-15 07:35:58
【问题描述】:

我有 WPF 窗口,其中的 DataGrid 在我的数据上下文中将 Items Source 设置为 BindingList 集合。 DataGrid 和绑定工作得很好,项目显示并删除了我如何更改我的模型。还连接了模型中 BindingList 集合的 ListChanged 事件的处理程序。然后,当用户在 DataGrid 中输入项目时,我们可以将模型与已保存的数据进行比较(如果模型更新,则启用保存按钮)。 DataGrid 中的项目也有验证规则。例如,当用户输入无效字符作为名称时,项目会得到红色标记。然后我们也只是禁用保存。

但是现在我有新的要求来检查 DataGrid 中是否有多个具有相同名称的项目,并在 DataGrid 中用红色标记它们 - 在用户输入项目时也是如此。

由于模型已经实现了 IDataErrorInfo,我可以很容易地发现模型的集合中确实存在重复项。但是如何在 DataGrid 中仅标记具有重复名称的项目?据我了解,这是首先验证组(DataGrid),然后根据该规则标记特定项目,但我完全被阻止,因为不知道如何在 MVVM 和 WPF 中正确实现它......

【问题讨论】:

    标签: c# wpf validation mvvm datagrid


    【解决方案1】:

    我有一些与此类似的实现。下面是未经测试的代码

    例子

    pubilic class ViewModel 
    {
         ObservableCollection<ViewModelDetail> Details { get; set; }
    }
    
    public class ViewModelDetail 
    {
         private readonly ViewModel parent;
         public class ViewModelDetail(ViewModel parent) 
         {
             this.parent = parent;
         }
    
     private string name;
     public string Name 
     {
         get{ return this.name; }
         set 
         {
            if(this.parent.Details.Where(d => d.Name == value).Count() > 0)
              SetError("Name", "Duplicate name");
           else
             this.name = value;
         }
     }      
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-09
      • 2018-09-06
      • 2011-09-29
      • 2011-06-29
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      相关资源
      最近更新 更多