Hello @Vivek Rao ,
Welcome to Microsoft Q&A!
To use ContentDialog
in winui3 you need to set the XamlRoot. By default, content dialogs display modally relative to the root ApplicationView. When you use ContentDialog
inside of either an AppWindow, 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.
Since there is no loading event in MainWindow and we can't set the XamlRoot in App::OnLaunched
, we need to use Page
as the contents of the MainWindow. The code is as follows, hopefully it will meet your needs.
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="DialogBoxTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:DialogBoxTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="DialogBoxTest">
<Page Loading="Page_Loading">
<StackPanel Loading="StackPanel_Loading" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
</StackPanel>
</Page>
</Window>
#include "pch.h"
#include "MainWindow.xaml.h"
#if __has_include("MainWindow.g.cpp")
#include "MainWindow.g.cpp"
#endif
using namespace winrt;
using namespace Windows::Foundation;
using namespace Microsoft::UI::Xaml;
using namespace Microsoft::UI::Xaml::Controls;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace winrt::DialogBoxTest::implementation
{
int32_t MainWindow::MyProperty()
{
throw hresult_not_implemented();
}
void MainWindow::MyProperty(int32_t /* value */)
{
throw hresult_not_implemented();
}
void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
{
myButton().Content(box_value(L"Clicked"));
}
fire_and_forget MainWindow::Page_Loading(winrt::Microsoft::UI::Xaml::FrameworkElement const& sender, winrt::Windows::Foundation::IInspectable const& args)
{
ContentDialog dialog;
dialog.Title(box_value(L"Test"));
dialog.Content(box_value(L"Welcome! "));
dialog.PrimaryButtonText(L"OK");
dialog.SecondaryButtonText(L"Cancel");
dialog.XamlRoot(myButton().XamlRoot());
auto cdr = co_await dialog.ShowAsync();
if (cdr == ContentDialogResult::Primary)
{
//do sth
}
else if (cdr == ContentDialogResult::Secondary)
{
this->Close();
}
}
}
Thank you.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.