Search code examples
windows-runtimec++-winrt

WinRT/C++ Get parent Page control of the Page inside the Frame


Best way to get parent Page control from Page inside Frame on desktop application built with WinRT/C++ UI.

Illustration:

MainPage
    ^^Frame
        ^^SecondPage
            ^^Frame
                ^^ThirdPage
                    ^^Keep going

So, how to get MainPage control from SecondPage or even from ThirdPage onwards.


Solution

  • You can use the VisualTreeHelper to navigate the visual tree. The following implementation goes up the visual tree starting at a root element, and returns an element that matches the requested ancestor_type, or a null com_ptr if there isn't any that matches:

    template <typename ancestor_type>
    auto find_ancestor(::winrt::Windows::UI::Xaml::DependencyObject root) noexcept
    {
        auto ancestor { root.try_as<ancestor_type>() };
        while (!ancestor && root)
        {
            root = ::winrt::Windows::UI::Xaml::Media::VisualTreeHelper::GetParent(root);
            ancestor = root.try_as<ancestor_type>();
        }
        return ancestor;
    }
    

    You can use this to move from Page to Page, skipping over the intermediate Frame's until you are at the top of the tree.