如何从视图模型显示弹出窗口。毛伊岛

问题描述 投票:0回答:2

我正在使用 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 和依赖注入来初始化我的对象。

c# xamarin maui
2个回答
7
投票

“此讨论”中描述了一种这样做的方法。您基本上可以将弹出窗口的显示包装在服务中。

创建界面
  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); } }
不要忘记在您的
    MauiProgram.cs
  1. 中注册它
    
  2. services.AddTransient<IPopupService, PopupService> ();
将服务注入到您的视图模型中并使用它
  1. public MainViewModel(IPopupService popupService) { this.popupService = popupService; } // and then somewhere (probably in a Command)... popupService.ShowPopup(popup);
我们还致力于在工具包本身中添加类似的内容,以便您不必在项目中自己编写这些内容。您可以在
此处

追踪进度。


0
投票

await Shell.Current.CurrentPage.DisplayAlert("Alert", "请提供密码", "OK");

© www.soinside.com 2019 - 2024. All rights reserved.