Binding to Missing Child Collection Objects

Binding to Missing Child Collection Objects

Old forum URL:

jjhartma posted on Thursday, October 01, 2009

I'm working on a form in a WPF app where it was requested to bind 3 text boxes to a property in a child collection object, and have those 3 fields bind to specific children.  The collection may or may not contain all 3 objects.

The idea I've had so far is to use a this[] member on the collection to chose which object.  So ParentObject.Children['A'].ChildProperty, ParentObject.Children['B'].ChildProperty, etc.

That all works, however if the object doesn't exist there is nothing to bind to.  I'd really like it if someone enters a value in a field where the object doesn't exist in the collection, that object is then created.

What's the best way to handle this?

Right now I'm stuck and thinking that my options are:

1.) Enforcing that those 3 children have to exist for every record and possibly writing a script to run through the database and create all those records.
2.) Create the missing objects on the fly if they don't exist when the this[] method is called.
3.) Create the missing objects when the data is loaded from the database in the DataPortal.

I guess I could also not use binding on those fields and write code-behind that handles the values and creating the objects, but that seems like a lot of unneeded work.

Has anyone else tackled something like this and can give me some advice?


kenb replied on Thursday, October 01, 2009

Since you're only dealing with three properties, you might consider putting them as properties on your collection object.  Something like ParentObject.Children.GetChildPropertyN or ParentObject.Children.GetChildProperty(N).  That method could handle the special cases where the child object doesn't actually exist.

jjhartma replied on Friday, October 02, 2009

This is very similar to adding a this[] method to the child collection, and it works. The only problem I have with using this[] in the collection or adding a function to the collection is that I don't have access to the parent object to get the Id field to add to my new child object.

I ended up adding a GetChildPropertyA type to the parent object, so that the parent object can create the new child and pass in it's Id at the same time.

The problem I have with this solution is that the object is then marked IsNew and so the parent object then believes that it needs to be saved.  I'm now trying to figure out if I can mark the new object old, so that it's only saved if data is actually entered into it.  I'm thinking I'm going to need a special factory method for that.

Copyright (c) Marimer LLC