How to get the parent of an object in WinUI3 with C++/WinRT?
See the question and my original answer on StackOverflowYou need to use the VisualTreeHelper Class to traverse the visual tree. Here is a C++/WinRT utility to walk the parents recursively:
template <typename T>
T GetParent(DependencyObject obj)
{
if (!obj)
return nullptr;
auto parent = Microsoft::UI::Xaml::Media::VisualTreeHelper::GetParent(obj);
if (!parent)
return nullptr;
auto parentAs = parent.try_as<T>();
if (parentAs)
return parentAs;
return GetParent<T>(parent);
}
And it's C# counterpart for what it's worth:
public static T GetParent<T>(DependencyObject obj) => (T)GetParent(obj, typeof(T));
public static object GetParent(DependencyObject obj, Type type)
{
if (obj == null)
return null;
var parent = VisualTreeHelper.GetParent(obj);
if (parent == null)
return null;
if (type.IsAssignableFrom(parent.GetType()))
return parent;
return GetParent(parent, type);
}
So you would call it like this:
void MainWindow::Button_Click(IInspectable const& sender, RoutedEventArgs const&)
{
auto listView = GetParent<Controls::ListView>(sender.try_as<DependencyObject>());
}