microsoft-ui-xaml: Unable to display ContentDialog. This element is already associated with a XamlRoot

Describe the bug

I have a custom MVVM framework with a ContentDialogService for displaying ContentDialogs inside a ViewModel. However, the ContentDialog requires the XamlRoot property to be set, however the MainWindow’s XamlRoot is always null when I debug. and I get this error:

An exception of type 'System.ArgumentException' occurred in System.Private.CoreLib.dll but was not handled in user code
WinRT 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.
Value does not fall within the expected range.

Below is my code for the ContentDialogService, MainWindow XAML, and MainWindow Code-Behind.

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using System;
using System.Threading.Tasks;

namespace Nickvision.WinUI.MVVM.Services
{
    /// <summary>
    /// A service that contains methods for working with content dialogs
    /// </summary>
    public class ContentDialogService : IContentDialogService
    {
        private XamlRoot _mainXamlRoot;

        /// <summary>
        /// Constructs a ContentDialogService
        /// </summary>
        /// <param name="mainXamlRoot">The main window's content's XamlRoot to display the ContentDialog</param>
        public ContentDialogService(XamlRoot mainXamlRoot) => _mainXamlRoot = mainXamlRoot;

        /// <summary>
        /// Shows a content dialog
        /// </summary>
        /// <param name="text">The text of the content dialog</param>
        /// <param name="title">The title of the content dialog</param>
        /// <param name="closeButtonText">The text of the close button</param>
        /// <param name="primaryButtonText">The text of the primary button (optional)</param>
        /// <param name="secondaryButtonText">The text of the secondary button (optional)</param>
        /// <returns>The ContentDialogResult</returns>
        public async Task<ContentDialogResult> ShowAsync(string text, string title, string closeButtonText, string primaryButtonText = null, string secondaryButtonText = null)
        {
            var dialog = new ContentDialog()
            {
                Title = title,
                Content = text,
                CloseButtonText = closeButtonText,
                PrimaryButtonText = primaryButtonText,
                SecondaryButtonText = secondaryButtonText,
                XamlRoot = _mainXamlRoot
            };
            return await dialog.ShowAsync();
        }

        /// <summary>
        /// Shows a custom content dialog
        /// </summary>
        /// <typeparam name="T">A ViewModelBase</typeparam>
        /// <param name="viewModel">The ViewModel representing the ContentDialog</param>
        /// <returns>The ContentDialogResult</returns>
        public async Task<ContentDialogResult> ShowAsync<T>(T viewModel) where T : ViewModelBase
        {
            var dialog = ViewLocator.ContentDialogFromViewModel(viewModel);
            dialog.XamlRoot = _mainXamlRoot;
            return await dialog.ShowAsync();
        }
    }
}
<Window
    x:Class="NickvisionWinApp.Views.MainWindowView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:NickvisionWinApp.Views"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" Activated="Window_Activated">

    <NavigationView Name="NavigationView" PaneDisplayMode="Top" IsBackButtonVisible="Collapsed" IsSettingsVisible="False" SelectedItem="{x:Bind ViewModel.SelectedNavigationItem, Mode=TwoWay}">
        <NavigationView.MenuItems>
            <NavigationViewItem Content="Home" Icon="Home" Tag="Home" IsSelected="True"/>
        </NavigationView.MenuItems>

        <NavigationView.FooterMenuItems>
            <NavigationViewItem Icon="Setting" Tag="Settings"/>
        </NavigationView.FooterMenuItems>

        <Frame Content="{x:Bind ViewModel.SelectedPage, Mode=TwoWay}"/>
    </NavigationView>
</Window>
using Microsoft.UI.Xaml;
using Nickvision.WinUI.Helpers;
using Nickvision.WinUI.MVVM.Services;
using NickvisionWinApp.ViewModels;

namespace NickvisionWinApp.Views
{
    public sealed partial class MainWindowView : Window
    {
        public MainWindowViewModel ViewModel { get; private set; }

        public MainWindowView()
        {
            InitializeComponent();
            ViewModel = new MainWindowViewModel(new ContentDialogService(NavigationView.XamlRoot), new ProgressDialogService(NavigationView.XamlRoot));
            //this.Content.XamlRoot is also null
            Title = ViewModel.Title;
        }

        private void Window_Activated(object sender, WindowActivatedEventArgs args) => this.Maximize();
    }
}

Steps to reproduce the bug

Steps to reproduce the behavior:

  1. Create a new WinUI in Desktop application
  2. Download and reference the Nickvision.WinUI Nuget Package. (When you try to build you’ll get an error. See Issue #4983 . You’ll have to manually add these two files to the Nuget package (Steps on issue #4454) https://we.tl/t-RlUTQP9xrn)
  3. Create a button and click event inside the MainWindow
  4. Inside the click event code:
IContentDialogService service = new ContentDialogService(this.Content.XamlRoot);
await service.ShowAsync();
  1. Run the application and click the button and you’ll get the error:
An exception of type 'System.ArgumentException' occurred in System.Private.CoreLib.dll but was not handled in user code
WinRT 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.
Value does not fall within the expected range.

Expected behavior

The ContentDialog should be displayed correctly, without errors.

Version Info

WinUI 3 - Project Reunion 0.5.6 Windows 10 V20H2

NuGet package version: [WinUI 3 - Project Reunion 0.5: 0.5.6] [Nickvision.WinUI V2021.5.0.6-beta]

Windows app type:

UWP Win32
Yes
Windows 10 version Saw the problem?
Insider Build (xxxxx)
October 2020 Update (19042) Yes
May 2020 Update (19041)
November 2019 Update (18363)
May 2019 Update (18362)
October 2018 Update (17763)
April 2018 Update (17134)
Fall Creators Update (16299)
Creators Update (15063)
Device form factor Saw the problem?
Desktop Yes
Xbox
Surface Hub
IoT

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 22 (2 by maintainers)

Most upvoted comments

As per the docs, there is a need to manually set the XamlRoot on the dialog to the root of the XAML host.

contentDialog.XamlRoot = elementAlreadyInMyAppWindow.XamlRoot;
await contentDialog.ShowAsync();

Microsoft Documentation Link

Of course, that link is a 404 these days. It’s been a whole seven months, I guess it’s too much to expect for docs to be that long-lived.

I found this documentation link (updated 07/08/2022) useful. I tried and it works. As the docs said, just manually set the XamlRoot of the ContentDialog as the XamlRoot of one of the elements, or the content, of the windows itself. The reason is:

By default, content dialogs display modally relative to the root ApplicationView. When you use ContentDialog inside of either an AppWindow or a XAML Island, you need to manually set the XamlRoot on the dialog to the root of the XAML host.

As per the docs, there is a need to manually set the XamlRoot on the dialog to the root of the XAML host.

contentDialog.XamlRoot = elementAlreadyInMyAppWindow.XamlRoot;
await contentDialog.ShowAsync();

Microsoft Documentation Link

Hey folks, sorry for not noticing this issue earlier. The XamlRoot property only gets set when the element in question gets loaded into a visual tree - that’s how we know what tree of XAML content it’s associated with. For a UIElement this makes sense, as it could be added to any tree so we can’t infer it until it really is in one.

We should consider exposing a Window.XamlRoot property which could be more eagerly available for scenarios like this (@marb2000 please consider that).

For now, what you should do is wait for Window.Content.Loaded to be raised, at which point Window.Content.XamlRoot will be valid - this is true of any UIElement, not just Window.Content, but that’s your use case in the code sample above.

@nlogozzo - could you see if that works for your case?

The XamlRoot property only gets set when the element in question gets loaded into a visual tree - that’s how we know what tree of XAML content it’s associated with.

Thank you bro. Austin-Lamb. You saved my time.

@mqudsi , every now an then kick back. we all build applications piece by piece. Sometimes by tiny pieces, hence these projects shall become a hobby rather than a duty at these stages.

Temporary Fix: Don’t use Activated event of Window. Instead, create a Loaded event for the Grid (or whatever control you have` for the window.