2

I am using Nuget CommunityToolkit.Maui.Views. I my Maui application I also using viewModels. Now I would like to show my custom dialog from viewmodel method. But

this.ShowPopup(new DialogPopup());

Can by invoke only on Page object.

I can assign value Page to property in my viewModel, but I am not sure this is the best option to implement it:

private readonly MainViewModel _mainViewModel;
public MainPage(MainViewModel vm)
{
    InitializeComponent();
    BindingContext = vm;
    _mainViewModel = vm;
    _mainViewModel.Page = this;
}

and in view model

public Page Page { get; set; }

and

Page.ShowPopup(new DialogPopup());

ShowPopup method look like this:

public static void ShowPopup<TPopup>(this Page page, TPopup popup) where TPopup : Popup {...}

How should I implement it to be able use this ShowPupup method in my view model?

I am using Net 7.0 and dependency injection to initialize my object.

Silny ToJa
  • 1,815
  • 1
  • 6
  • 20
  • https://stackoverflow.com/questions/73471610/passing-data-to-communitytoolkit-maui-popup/73737949#73737949 this could help! – Leandro Toloza Mar 13 '23 at 13:28

1 Answers1

7

One way of doing so is described in this discussion. You would basically wrap the showing of the popup in a service.

  1. Create Interface
public interface IPopupService
{
    void ShowPopup(Popup popup);
}
  1. create implementation
public class PopupService : IPopupService
{
    public void ShowPopup(Popup popup)
    {
        Page page = Application.Current?.MainPage ?? throw new NullReferenceException();
        page.ShowPopup(popup);
    }
}
  1. Don't forget to register it in your MauiProgram.cs
services.AddTransient<IPopupService, PopupService> ();
  1. Inject the service into your view model and use it
    public MainViewModel(IPopupService popupService)
    {
        this.popupService = popupService;
    }

    // and then somewhere (probably in a Command)...
    popupService.ShowPopup(popup);  

We're also working on adding something like this in the Toolkit itself so that you don't have to write this yourself in your project. You can track the progress of that here.

Gerald Versluis
  • 30,492
  • 6
  • 73
  • 100