asynchronouscastingpopuptaskmaui

C# How to cast Task<object?> to a specific type?


I've encountered a problem while building a PopUp in .NET MAUI. According to their documentation one can pass data with onPresenting but also receive data asynchronously via CloseAsync() in the PopupViewModel.

In the ViewModel calling the Popup one is awaiting the result:

var result = await _popupService.ShowPopupAsync<PopupViewModel>(onPresenting: async viewModel => await viewModel.BuildPopup(Data));

The type of result is Task<object?> which seems to be an idiosyncrasy of .NET MAUI for Popups. Now, how can I cast this object if I know for sure the object is going to be of the type List<ImageSource> while upholding the asynchrony?

I've tried type casting as I'm used to via (List<ImageSource>) in front of the call, but then I need to use .Result and lose the asynchrony which breaks other parts.


Solution

  • Let string "result" be the object to pass from (CommunityToolkit) Popup.

    In code behind (e.g. a Page) from where popup is shown:

    string str = (string)await this.ShowPopupAsync(popup);
    

    In popup code behind:

    Close("result");
    

    The string str should now have the value "result".