我正在使用 Nuget CommunityToolkit.Maui.Views。我的毛伊岛应用程序我也使用 viewModels。现在我想通过 viewmodel 方法显示我的自定义对话框。但是
this.ShowPopup(new DialogPopup());
只能在 Page 对象上调用。
我可以将值 Page 分配给我的 viewModel 中的属性,但我不确定这是实现它的最佳选择:
private readonly MainViewModel _mainViewModel;
public MainPage(MainViewModel vm)
{
InitializeComponent();
BindingContext = vm;
_mainViewModel = vm;
_mainViewModel.Page = this;
}
在视图模型中
public Page Page { get; set; }
和
Page.ShowPopup(new DialogPopup());
ShowPopup 方法如下所示:
public static void ShowPopup<TPopup>(this Page page, TPopup popup) where TPopup : Popup {...}
我应该如何实现它才能在我的视图模型中使用此 ShowPupup 方法?
我正在使用 Net 7.0 和依赖注入来初始化我的对象。
“此讨论”中描述了一种这样做的方法。您基本上可以将弹出窗口的显示包装在服务中。
创建界面public interface IPopupService
{
void ShowPopup(Popup popup);
}
public class PopupService : IPopupService
{
public void ShowPopup(Popup popup)
{
Page page = Application.Current?.MainPage ?? throw new NullReferenceException();
page.ShowPopup(popup);
}
}
MauiProgram.cs
中注册它
services.AddTransient<IPopupService, PopupService> ();
public MainViewModel(IPopupService popupService)
{
this.popupService = popupService;
}
// and then somewhere (probably in a Command)...
popupService.ShowPopup(popup);
我们还致力于在工具包本身中添加类似的内容,以便您不必在项目中自己编写这些内容。您可以在此处
await Shell.Current.CurrentPage.DisplayAlert("Alert", "请提供密码", "OK");