question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to display ContentDialog. This element is already associated with a XamlRoot

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:2
  • Comments:20 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
jamiehankinscommented, Jun 25, 2022

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.

2reactions
RajeetGoyalcommented, Dec 3, 2021

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

Read more comments on GitHub >

github_iconTop Results From Across the Web

C# WinUI 3 Desktop Application Issue with ContentDialog ...
I want to use a contentdialog to display error messages. ... error - 0x80070057 : 'This element is already associated with a XamlRoot, ......
Read more >
ContentDialog Class (Windows.UI.Xaml.Controls)
To do so, set the ContentDialog's XamlRoot property to the same XamlRoot as an element already in the AppWindow or XAML Island, as...
Read more >
ContentDialog Class (Microsoft.UI.Xaml.Controls)
To do so, set the ContentDialog's XamlRoot property to the same XamlRoot as an element already in the XAML tree. If the ContentDialog...
Read more >
A Dialog Service for WinUI 3 | XAML Brewer, by Diederik Krols
You get a “This element is already associated with a XamlRoot, it cannot be associated with a different one until it is removed...
Read more >
A deep-dive into WinUI 3 in desktop apps for Windows 10
XAML Islands was our first solution to enable developers to use UWP XAML inside their desktop (Win32) apps. Within a couple of months...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found