如何使用ViewModelCloser关闭ViewModel的View?

Ste*_*han 3 c# mvvmcross xamarin

在 MvvmCross v3, CustomerManagement 示例中,该方法void RequestClose(IMvxViewModel viewModel)关闭顶部View。你如何关闭Viewa 的ViewModel呢?

Stu*_*art 5

我不会使用 ViewModelCloser 方法 - 尽管如果您愿意,可以对其进行扩展。

MvvmCross v3 删除了之前的CloseViewModel方法——因为它并没有真正适用于所有平台和所有演示样式——适用于所有导航控制器、拆分视图、选项卡、浮出控件、弹出窗口、对话框等。

为了替换它,v3 引入了一个新的 ViewModel 调用:

    protected bool ChangePresentation(MvxPresentationHint hint)
Run Code Online (Sandbox Code Playgroud)

这在 UI 中与 IMvxViewPresenter 方法匹配:

    void ChangePresentation(MvxPresentationHint hint);
Run Code Online (Sandbox Code Playgroud)

要使用它,您需要:

  1. 创建一个新的提示类 - 例如 public class CustomPresentationHint : MvxPresentationHint { /* ... */ }

  2. 在每个 UI 项目中,提供一个自定义演示者(通常通过CreateViewPresenter()在您的Setup.cs类中覆盖) - 并在该自定义演示者中处理ChangePresentationHint调用:

          public void ChangePresentation(MvxPresentationHint hint)
          {
              if (hint is CustomPresentationHint)
              {
                   // your custom actions here
                   // - which may involve interacting with the RootFrame, with a NavigationController, with the AndroidFragment manager, etc
              }
          }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在您的视图模型中,您可以CustomPresentationHint在需要时发送一个。

我意识到这比 vNext 需要的“更多的工作”,但希望它是一种更灵活、更强大的方法。