views:

1425

answers:

2

I have written a custom Silverlight control based on Control. I have two DependencyProperties called Top and Bottom which both hold child controls for a specific layout display. I then use a ControlTemplate to arrange these two controls into a grid, placing one on the 0 row and the other on the 1 row. The problem I have is that I cannot seem to figure out how to get each child control's Parent property to point to my custom control. When I inspect each control at run-time, the Parent property of each is null.

This is a simple example, but I think you can see the general problem. I have a number of more complex controls that all share this problem. I know there is some magic I am missing. If a ContentControl's Content property is set to some child it is somehow setting that child's parent to itself.

Edit: A little more info

In WPF, one might use functions like AddVisualChild(), RemoveVisualChild(), AddLogicalChild(), RemoveLogicChild() to manage parent/child relationships, but these functions are not available in Silverlight.

A: 

The Parent property cannot be arbitrary, it reflects the real parent of the control for use when rendering.

From MSDN: Parent may be a null reference (Nothing in Visual Basic) in cases where an element was instantiated, but is not attached to any logical tree that eventually connects to the page level root element, or the application object.

...

Changing an element's parent is typically only done through manipulation of collections, by using dedicated add or remove methods, or through setting content properties of elements.

BC
Right. So when you are writing a custom control, how do you replicate what is going by setting a Content property or adding an element as a child in a Children collection?
Jason Jackson
+2  A: 

After quite a bit of research I believe that this is not possible. I was able to recurse through the Visual Tree instead of the Logic Tree using the VisualTreeHelper to accomplish my ultimate goal.

Jason Jackson
Correct. Parent is set by the presentation framework itself when creating the visual tree.
Jeff Wilcox
I feel a little silly marking my own answer as correct, but after quite some time I haven't seen a better answer.
Jason Jackson