Reputation: 11
I am looking for a way to close popup from viewmodel or service created to show or close popup. Popup close event code is handled at code behind of popup page. we have old xamarin application which are migrating to .net maui in that we have used popup plugin for popup, but currently we want to less reliant on any other plugins for popup. Earlier the plugins used interface to expose open and close event for popup. In toolkit popup I don't found any such interface or way to do so.
I tried using code behind function but there is no way I am able to trigger that event from service used
Upvotes: 1
Views: 1278
Reputation: 8245
Let's say you have a Button placed in Popup
and when clicking the Button, the Popup close.
<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Name="this">
...
<Button Text="close" Command="{Binding CloseCommand}" CommandParameter="{x:Reference this}"/>
</toolkit:Popup>
We can use Bindings for CommandParameter
to pass the Popup
to ViewModel, thus we can easily close it in ViewModel,
public Command CloseCommand
{
get
{
return new Command((p) =>
{
Popup popup = p as Popup;
popup.CloseAsync();
});
}
}
For more info, please refer to Popup.
Upvotes: 0
Reputation: 111
I struggled with this as well while creating an activity indicator popup, as far as I know the only way to get this to work is to publish an event to which your popup code behind is subscribed to and closed itself. I ended up creating a service to make opening and closing the activity popup easier:
public class ActivityIndicatorService : IActivityIndicatorService
{
private readonly IPopupService _popupService;
public ActivityIndicatorService(IPopupService popupService)
{
_popupService = popupService;
}
public void Close()
{
MessagingCenter.Send(this, Events.CloseActivityPopup);
}
public async Task Open()
{
_popupService.ShowPopupAsync<ActivityIndicatorPopupViewModel>();
}
}
and in the code behind:
public partial class ActivityIndicatorPopup : Popup
{
public ActivityIndicatorPopup(ActivityIndicatorPopupViewModel vm)
{
InitializeComponent();
BindingContext = vm;
MessagingCenter.Subscribe<ActivityIndicatorService>(this, Events.CloseActivityPopup, async (_) => await CloseEventHandler());
}
private async Task CloseEventHandler()
{
await CloseAsync();
}
}
Upvotes: 0