xamarin 如何显示viewmodel的弹出窗口,Maui

1szpjjfi  于 2023-03-16  发布在  其他
关注(0)|答案(1)|浏览(370)

我正在使用Nuget CommunityToolkit.Maui.Views。我的Maui应用程序也在使用viewModels。现在我想从viewmodel方法显示我的自定义对话框。但是

this.ShowPopup(new DialogPopup());

只能在Page对象上调用。
我可以在我的viewModel中将值Page赋给property,但我不确定这是实现它的最佳选择:

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方法?
我使用Net7.0和依赖注入来初始化我的对象。

bxgwgixi

bxgwgixi1#

this discussion中介绍了一种方法,基本上就是将弹出窗口的显示封装在服务中。
1.创建接口

public interface IPopupService
{
    void ShowPopup(Popup popup);
}

1.创建实现

public class PopupService : IPopupService
{
    public void ShowPopup(Popup popup)
    {
        Page page = Application.Current?.MainPage ?? throw new NullReferenceException();
        page.ShowPopup(popup);
    }
}

1.不要忘记在MauiProgram.cs中注册它

services.AddTransient<IPopupService, PopupService> ();

1.将服务注入视图模型并使用它

public MainViewModel(IPopupService popupService)
    {
        this.popupService = popupService;
    }

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

我们也在努力在Toolkit中添加类似的东西,这样你就不必在你的项目中自己写这些东西了,你可以跟踪here的进度。

相关问题