Search code examples
xamluwpc++-winrtwinui

How do I get the typename of an arbitrary XAML FrameworkElement?


For an arbitrary WinUI/UWP FrameworkElements in C++/WinRT, how can I get its concrete type name (i.e. what type of control it is)?

In my code, I have a function that works with FrameworkElements (and I'm navigating the visual tree, so I genuinely have no clue which elements I'm working with):

void DoSomethingWithElement(winrt::FrameworkElement const& current)
{
  // ... I have no idea what current is at this point
}

For debugging, I'm trying to understand more information about the control, but the Visual Studio debugger isn't giving me a ton of info:

locals view current only has raw view

And the Command Window isn't helpful either:

>? current.IsLoaded()
class "winrt::Microsoft::UI::Xaml::FrameworkElement" has no member "IsLoaded"

How can I get more information about this control?


Solution

  • You can use winrt::get_class_name:

    const auto className = winrt::get_class_name(current)
    // => "Microsoft.UI.Xaml.Controls.TextBox" etc
    

    You can even call it from the Command Window:

    >? winrt::get_class_name(child)
    L"Microsoft.UI.Xaml.Controls.TextBox"
        size: 34
        [ptr]: 0x000001cf8f3d3cbc L"Microsoft.UI.Xaml.Controls.TextBox"
        [Raw View]: {m_handle={m_value=0x000001cf8f3d3ca0 {flags=0 length=34 padding1=2449805792 ...} } }