I’m writing an app for Windows 8 Metro and am having a problem understanding how Canvas’ child-parent relationship works. It seems that when I add one canvas to the children of another, the subcanvas’ ->parent property is equal to null until the parent canvas is added to the visual tree. Below is some sample code showing the problem.
Xaml::Controls::Canvas^ testCanvas = ref new Xaml::Controls::Canvas();
Xaml::Controls::Canvas^ childCanvas = ref new Xaml::Controls::Canvas();
testCanvas->Children->Append(childCanvas);
int size = testCanvas->Children->Size; // size will be equal to 1
if(!childCanvas->Parent)
{
// this code is executed because ->Parent is null. Why is parent here null??
}
aCanvasThatIsPartOfTheVisualTree->Children->Append(testCanvas);
if(!childCanvas->Parent)
{
// this code does not get executed because ->Parent is not null, now that testCanvas is part of the visual tree.
}
I’ve also tried using the VisualTreeHelper to get the parent:
Xaml::Controls::Canvas^ theParent = (Xaml::Controls::Canvas^)VisualTreeHelper::GetParent(childCanvas);
and the behavour remains: theParent is null before testCanvas is added to the visual tree, and not null after testCanvas is added to the visual tree.
If this is not a bug, can someone please tell me how to get a subcanvas’ parent without the parent being part of the visual tree? If it is a bug, are there any known workarounds? Thank you!
If you break apart the name of the
VisualTreeHelperyou will see that it is the “Visual Tree” helper. That means it is getting the visual parent of the element. If it isn’t currently part of the visual tree then it won’t have a parent as defined by theVisualTreeHelper.From here (on
VisualTreeHelper.GetParent):From here (on
FrameworkElement.Parentfrom which controls get theirParentproperty):