【问题标题】:Accessing ViewModel by inheriting a View in MvvmCross通过继承 MvvmCross 中的 View 访问 ViewModel
【发布时间】:2016-07-02 05:28:45
【问题描述】:

我想从一个不是 View 的类中访问我的 ViewModel。如果我执行以下操作可以吗?这是打破常规吗?

namespace MyApp
{
   public class GameView
   {
        protected new GameViewModel ViewModel
        {
            get { return (GameViewModel)base.ViewModel; }
        }
   }
}

// Derived class
namespace MyApp
{
    public class InAppPurchase: GameView
    {
         public void BuyCoins()
         { 
             ViewModel.PurchasedCoins += ViewModel.CoinsForSale;
         }
    }
}

【问题讨论】:

  • 在我看来这绝对违反了 MVVM 模式。我认为您有一个绑定到 GameViewModel 的 GameView。为什么要从 GameView 类继承?不知道具体场景,也无法解释清楚。
  • 这个问题主要是基于意见的。我的意见是你应该有一个 1:1 的 Views 到 ViewModels 的映射。您当前显示的代码违反了这一点,您可能必须在 View 中进行手动导航,而不是在 MvvmCross 中使用您的代码从 ViewModel 中进行导航。

标签: c# inheritance mvvm viewmodel mvvmcross


【解决方案1】:

如果您想从任何地方访问 ViewModel,您可能希望发送消息 (MvxMessage) 并在 ViewModel 中处理它们(使用 IMessenger 发布/订阅)。这是在 ViewModel 或 ViewModel 与其他组件(如 Mvvm 模式中的服务)之间进行通信的正确方式。

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多