Follow-on Question Regarding C++/WinRT WinUI 3 Content Dialog

142 views Asked by At

I have a follow-on question to this one: c-winrt-xaml-contentdialog. I'm trying to learn C++/WinRT and WinUI 3 by migrating the code from Petzold's "Programming Windows" 6th edition. I'm up to chapter 7, and am stuck on the "HowToAsync1" project. I created the standard WinUI 3 Desktop app and am trying to use this for the click handler:

    void MainWindow::OnButtonClick(IInspectable const&, RoutedEventArgs const&)
    {
        ContentDialog dialog;
        dialog.Title(box_value(L"title"));
        dialog.Content(box_value(L"content"));
        dialog.PrimaryButtonText(L"Red");
        dialog.SecondaryButtonText(L"Blue");
        dialog.CloseButtonText(L"Close");
        dialog.XamlRoot(myButton().XamlRoot());

        IAsyncOperation<ContentDialogResult> result = /*co_await*/ dialog.ShowAsync();
        ContentDialogResult cdr = result.GetResults();

        if (cdr == ContentDialogResult::Primary)
        {
            SolidColorBrush myBrush{ Microsoft::UI::Colors::Red() };
            contentGrid().Background(myBrush);
        }
        else if (cdr == ContentDialogResult::Secondary)
        {
            SolidColorBrush myBrush{ Microsoft::UI::Colors::Blue() };
            contentGrid().Background(myBrush);
        }
    }

The code compiles and runs, but there are 2 problems:

  1. cdr is returned as ContentDialogResult::None regardless of which button I press. I discovered that this is because the if statement executes before the dialog even appears, which leads to problem #2:
  2. If I uncomment the "co_await" that Kenny Kerr suggested, the compiler complains that class std::corouting_traits<…> has no member “promise_type”, and the code won't compile.

Suggestions?

1

There are 1 answers

0
dr_eck On BEST ANSWER

Here's the working code, incorporating Raymond Chen's suggestion:

    winrt::fire_and_forget MainWindow::OnButtonClick(IInspectable const&, RoutedEventArgs const&)
    {
        ContentDialog dialog;
        dialog.Title(box_value(L"title"));
        dialog.Content(box_value(L"content"));
        dialog.PrimaryButtonText(L"Red");
        dialog.SecondaryButtonText(L"Blue");
        dialog.CloseButtonText(L"Close");
        dialog.XamlRoot(myButton().XamlRoot());

        auto cdr = co_await dialog.ShowAsync();

        if (cdr == ContentDialogResult::Primary)
        {
            SolidColorBrush myBrush{ Microsoft::UI::Colors::Red() };
            contentGrid().Background(myBrush);
        }
        else if (cdr == ContentDialogResult::Secondary)
        {
            SolidColorBrush myBrush{ Microsoft::UI::Colors::Blue() };
            contentGrid().Background(myBrush);
        }
    }