我正在为 Windows 8 Metro 编写应用程序,但在理解 Canvas 的子父关系如何工作时遇到了问题。似乎当我将一个画布添加到另一个画布的子画布时,子画布的 ->parent 属性等于 null ,直到将父画布添加到可视树中。下面是一些显示问题的示例代码。
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.
}
我也尝试使用 VisualTreeHelper 来获取父级:
Xaml::Controls::Canvas^ theParent = (Xaml::Controls::Canvas^)VisualTreeHelper::GetParent(childCanvas);
并且行为仍然存在:在将 testCanvas 添加到可视化树之前 theParent 为空,并且在将 testCanvas 添加到可视化树后不为空。
如果这不是一个错误,有人可以告诉我如何在父级不属于可视化树的情况下获取子画布的父级吗?如果是错误,是否有任何已知的解决方法?谢谢!