3

I am develop a new app for Windows 11 in WinUI3 UWP, and I want show a dialog to provide a safe action like in this example of Microsoft Docs: https://learn.microsoft.com/en-us/windows/apps/design/controls/dialogs-and-flyouts/dialogs

private async void DisplayNoWifiDialog()
{
    ContentDialog noWifiDialog = new ContentDialog
    {
        Title = "No wifi connection",
        Content = "Check your connection and try again.",
        CloseButtonText = "Ok"
    };

    ContentDialogResult result = await noWifiDialog.ShowAsync();
}

When the user click in button on my MainPage.xaml show that Dialog and when user click on "ok" returns to MainPage.xaml, but when I run my program give me this error: "XamlRoot must be explicitly set for unparented popup"

How can I resolve this?

Thank you!

Luís
  • 157
  • 2
  • 10
  • [Read further in the documentation](https://learn.microsoft.com/en-us/windows/winui/api/microsoft.ui.xaml.controls.contentdialog?view=winui-3.0#contentdialog-in-appwindow-or-xaml-islands): "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. To do so, set the ContentDialog's XamlRoot property to the same XamlRoot as an element already in the AppWindow or XAML Island, as shown here." – Raymond Chen Jan 09 '22 at 17:22
  • I read that and use that code but give me error! The compiler dont know what if "elementAlreadyInMyAppWindow" – Luís Jan 09 '22 at 18:49
  • The name "elementAlreadyInMyAppWindow" is a placeholder for the name of " an element already in the AppWindow or XAML Island." – Raymond Chen Jan 09 '22 at 22:38

1 Answers1

4

It seems like that you are developing a WinUI3 app. As @Raymond Chen mentioned, you will have to add the XamlRoot property to the ContentDialog.

Xaml:

  <StackPanel x:Name="MyPanel" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
    <Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
</StackPanel>

Code-behind:

 private async void myButton_Click(object sender, RoutedEventArgs e)
    {
        ContentDialog noWifiDialog = new ContentDialog
        {
            Title = "No wifi connection",
            Content = "Check your connection and try again.",
            CloseButtonText = "Ok"
        };
        //set the XamlRoot property
        noWifiDialog.XamlRoot = MyPanel.XamlRoot;

        ContentDialogResult result = await noWifiDialog.ShowAsync();
    }
Roy Li - MSFT
  • 8,043
  • 1
  • 7
  • 13