【问题标题】:WinRT/C++ Get parent Page control of the Page inside the FrameWinRT/C++获取Frame内Page的父Page控件
【发布时间】:2021-12-15 20:35:03
【问题描述】:
在使用 WinRT/C++ UI 构建的桌面应用程序上从 Frame 内的 Page 获取父 Page 控件的最佳方式。
插图:
MainPage
^^Frame
^^SecondPage
^^Frame
^^ThirdPage
^^Keep going
那么,如何从 SecondPage 甚至从 ThirdPage 开始获取 MainPage 控件。
【问题讨论】:
标签:
windows-runtime
c++-winrt
【解决方案1】:
您可以使用VisualTreeHelper 来导航可视化树。以下实现从 root 元素开始沿可视化树向上,并返回与请求的 ancestor_type 匹配的元素,如果没有任何匹配项,则返回 null com_ptr:
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;
}
您可以使用它从Page 移动到Page,跳过中间的Frame,直到您位于树的顶部。