Friday, February 19, 2010

generic reparenting in Silverlight

If you have tried to detach an object from its parent in Silverlight you have undoubtedly discovered that this.Parent doesn't expose the Children collection and that most if not all of the code on the net requires knowledge of the type of the Parent. This inevitably leads to brittle code and introduces constraints on what type of container your control can be placed in.

Fortunatly .Net gives us a tool to write generic code in just this type of situation... reflection. So with that in mind I wrote a simple pair of functions that set or clear the parent of a Silverlight control as long as the Parent has a collection of UIElements named Children.

It should be possible to get rid of the (expensive) calls to MethodInfo.Invoke but as this code is code is called infrequently in my case I'm not that concerned with with the optimization. I'll leave it as an exercise to the reader to figure out this optimization if your use case is different.