locked
Canvas has no parent if not part of the visual tree?

    Question

  • Hi,

    I'm writing a 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. 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!

    James

    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.

    }




    • Edited by JamesTron Thursday, September 27, 2012 6:55 PM
    Thursday, September 27, 2012 6:49 PM

Answers

  • Answer can be found in QA on SO.
    • Marked as answer by JamesTron Friday, September 28, 2012 4:13 PM
    Friday, September 28, 2012 4:13 PM

All replies

  • .Parent is horrible property. Beter use the VisualTreeHelper->GetParent()
    Thursday, September 27, 2012 6:55 PM
  • Thank you for the suggestion, but unfortunately the behaviour is the same. I tried adding

    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.

    Any ideas?

    Thanks!


    • Edited by JamesTron Thursday, September 27, 2012 7:15 PM
    Thursday, September 27, 2012 7:14 PM
  • Answer can be found in QA on SO.
    • Marked as answer by JamesTron Friday, September 28, 2012 4:13 PM
    Friday, September 28, 2012 4:13 PM