I was monitoring my Twitter feed, like I always do, and saw a tweet come through asking about how to validate an object’s property against it’s parent ObservableCollection in the Infragistics XamDataGrid. What this person was trying to accomplish was to validate a duplicate item in his data source. They have a POCO object the implements the IDataErrorInfo interface, and an ObservableColletion<POCO> as the data source. They want to check the ObservableCollection<POCO> for a pre-existing item whenever a property value in a POCO changes. Obviously this is not a XamDataGrid issue, but rather an object design issue. So I decided to whip up a quick and dirty solution to solve this particular issue.
The approach I am going to take is to simply keep track of the parent collection from within the POCO object itself. I really like interfaces, so I started out by defining a simple interface my POCOs will implement.
Now let’s take a look at the simple POCO I will be using in this example.
Notice that we implement both the INotifyPropertyChanged interfaces as well as the IDataErrorInfo interface. The Next thing we need is a custom ObservableCollection to use as our data source.
Notice that we are casting our item as the IHasParent interface and setting the Parent property accordingly. The next thing we need to do is have our POCO class implement the IHasPerson interface.
Notice how we implemented the check for a duplicate last name. We simply checked to make sure we are dealing with the LastName property. Then we cast the Parent as an IList<Person> so that we can perform a simply LINQ query against it. We check the parent collection for any results that match the LastName property. If more than one is returned we have a duplicate.
So let’s test this baby using the XamDataGrid as the original poster was attempting to do. First create our UI.
Next let’s hook up some data to this bad boy:
Now let’s run the app, type a duplicate last name, and see what we get.
Cool. Works as expected. Now there are a number of ways to accomplish this task. There are even frameworks out there that have already solved this problem for you such as CSLA. I hope this simple approach helps you find a solution that works for you.