1
votes

I have WPF Window and inside it DataGrid which Items Source is set to BindingList collection in my data context. DataGrid and bindings works just fine, items show up and remove how I change my model. Have also hooked up handler for ListChanged event of BindingList collection in model. Then we can compare model with already persisted data while user types in items in DataGrid (and then enable save button if model is updated). Also have validation rules for items in DataGrid. For example, when user enters invalid characters for name, items gets red marking. We then also just disable save.

But now I have new requirement to check if there are multiple items in DataGrid with identical names and to mark them in DataGrid with red color - also while user types in items.

As model already implements IDataErrorInfo, I can easily find that duplicates do exist in collection in model. But how can I mark just that items with duplicated names in DataGrid? As I understand, this is in a way validation first of the group (DataGrid) and then marking of specific items based on that rule, but I'm completely blocked as have no idea how to implement it properly in MVVM and WPF...

1

1 Answers

1
votes

I have some implementation similiar to this. Untested code bellow

Example

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;
     }
 }      
}