WinUI3 / XAML - "This element is already associated with a XamlRoot..."

Rudolf Meier 291 Reputation points
2021-10-19T12:15:46.49+00:00

hi... I started working with WinUI3 and together with that I started working with XAML. Now... as long as I can use XAML to define everything and only implement the callbacks from buttons and things like that it works just fine. But now I want to create a CommandBarFlyout and a MenuFlyout ... once "attached" to a button, once just in the middle of the screen without a parent window.

How can I do this? Well, first I thought I have to load the flyout resource. So I do this:

winrt::Microsoft::UI::Xaml::Controls::Primitives::FlyoutBase pFlyout =
Application::Current().Resources().Lookup(winrt::box_value(L"FlyoutResource")).as<winrt::Microsoft::UI::Xaml::Controls::Primitives::FlyoutBase>();

(I have 2 resources defined in the App.xaml which are of type "MenuFlyout" and "CommandBarFlyout")

That's working and I get this element (pFlyout is not nothing).

Then I tryed to adapt the example code I found like this:

winrt::Microsoft::UI::Xaml::Controls::Primitives::FlyoutShowOptions options;
// fill those options somehow...

pFlyout.ShowAt(sender.as<winrt::Microsoft::UI::Xaml::FrameworkElement>(), options);

(sender is the sender parameter I get inside my click-handler for a button I made...)

and then it crashes with the information

This element is already associated with a XamlRoot, it cannot be associated with a different one until it is removed from the previous XamlRoot.

... so. Fine... what does this mean? What is a XamlRoot? Why do I need it? Why is it set? Who did set it? Is this XamlRoot set in this pFlyout? When does this happen? When I call the Lookup? Do I have to do it differently? Make a copy? what? how? why?

thanks for help and explanation... I really want to understand this

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
747 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 12,151 Reputation points Microsoft Vendor
    2021-10-20T01:47:25.83+00:00