How to Close the MauiCommunityToolkit Popup from Viewmodel
The MauiCommunityToolkit provides a convenient way to display popups in your Maui applications. However, you may encounter situations where you need to close the popup from the viewmodel. This can be achieved using various methods.
Method 1: Using a Task to Delay the Popup ClosurePopupPage p = new PopupPage(); Application.Current.MainPage.ShowPopup(p); await new TaskFactory().StartNew(() => { Thread.Sleep(5000); }); p.Close();
In this method, a new popup page is created and displayed using the ShowPopup
method. Then, a Task
is created to delay the closure of the popup for 5 seconds. After the delay, the Close
method is called to close the popup.
<Button Command="{Binding CloseClickCommand}" CommandParameter="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type mct:Popup}}}" Text="Close" />
public async Task CloseClickCommand(object obj) { if (obj is Popup popup) { popup.Close(); } }
This method involves creating a button with a command and command parameter. The command parameter is bound to the Popup
object, and the command is bound to a method in the viewmodel that closes the popup.
<toolkit:Popup x:Class="VSTORE.Views.Popups.UserAdresPopupView" xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit" xmlns:vm="clr-namespace:VSTORE.ViewModels.PopupsViewModel" x:Name="MYPOPUP" <Button Command="{Binding CloseCommand}" CommandParameter="{Binding Source={x:Reference MYPOPUP}}" Style="{StaticResource ConfirmButton}" Text="CLOSE" />
[RelayCommand] public async Task Close(Popup popup) { popup.Close(); await DisplayToast("Closed using button"); }
In this method, a reference to the Popup
object is created in XAML and bound to a command in the viewmodel. The command is then implemented in the viewmodel to close the popup.
The choice of method depends on the specific requirements of your application. Carefully consider the context and functionality you need to achieve when selecting the appropriate method for closing the popup from the viewmodel.