Open popup from view model #566
-
Is there a way to open popup from a viewmodel? The documentation indicates that it can only be opened from a ContentPage but I was wondering if there’s a workaround. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Pop up is UI element, but you can still call it from view model: |
Beta Was this translation helpful? Give feedback.
-
I think it depends on how much of an MVVM-Purist™ you are. 😉 I'm a pragmatist, so personally I'd be more than happy to go with the approach suggested by @VladislavAntonyuk. But if you are a purist and want to decouple UI elements from your ViewModels then another option would be to create a IPopupService which you inject into your ViewModels. Something like this: create interface public interface IPopupService
{
void ShowPopup(Popup popup);
} create implementation public class PopupService : IPopupService
{
public void ShowPopup(Popup popup)
{
Page page = Application.Current?.MainPage ?? throw new NullReferenceException();
page.ShowPopup(popup);
}
} don't forget to register it services.AddTransient<IPopupService, PopupService> (); inject service into your viewmodel and use it public PopupAnchorViewModel(IPopupService popupService)
{
this.popupService = popupService;
}
// and then somewhere (probably in a command)...
popupService.ShowPopup(popup); But that's a lot of code, and in reality, you probably aren't really achieving much. So yeah, for my money you could go with what @VladislavAntonyuk said, which is pretty much how it's done in the Sample App ViewModels. I just thought it would be interesting to discuss an alternate approach. |
Beta Was this translation helpful? Give feedback.
-
Closed as answered |
Beta Was this translation helpful? Give feedback.
I think it depends on how much of an MVVM-Purist™ you are. 😉 I'm a pragmatist, so personally I'd be more than happy to go with the approach suggested by @VladislavAntonyuk.
But if you are a purist and want to decouple UI elements from your ViewModels then another option would be to create a IPopupService which you inject into your ViewModels. Something like this:
create interface
create implementation
don't forget to register it
ser…