【问题标题】:Context in DotVVM inner ViewModel is nullDotVVM 内部 ViewModel 中的上下文为空
【发布时间】:2015-10-23 21:01:04
【问题描述】:

我正在制作一个 DotVVM 应用程序,我想在每个页面上显示注销按钮或登录表单。因此,我制作了使用 ViewModel 处理登录或注销的自定义控件。 由于我希望在每个页面上都有此控件,因此我将其放在了 .master 页面中。

我的 DotMaster 页面如下所示:

@viewModel MyApp.ViewModels.AppViewModelBase, MyApp
<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>{{value:Title}}</title>
   </head>
   <body>
       <nav class="navbar navbar-inverse navbar-default">
           ...
           <cc:LoginPanel DataContext="{value: LoginSection}"></cc:LoginPanel>
           ...
       </nav>
       ...
   </body> 
</html>

对应的 ViewModel AppViewModelBase 看起来像这样。

using System.Threading.Tasks;
using DotVVM.Framework.ViewModel;
using MyApp.ViewModels.Login;

namespace MyApp.ViewModels
{
   public class AppViewModelBase : DotvvmViewModelBase
   {
      public string SubpageTitle { get; set; }

      public string Title { get { return string.Format("{0} - {1}", LogoText, SubpageTitle); } }

      public LoginSection LoginSection { get; set; } = new LoginSection();
      ...
   }
}

我的 LoginSection ViewModel 也继承自 DotvvmViewModelBase,问题是,LoginSection 的 Context 属性永远不会被填充并保持为空。 我应该手动设置内部 ViewModels 的上下文吗?我还注意到 AppViewModelBase 的上下文没有在它的基本构造函数中设置,而是在稍后的某个地方设置。

此用例的最佳做法是什么?

【问题讨论】:

    标签: c# mvvm dotvvm


    【解决方案1】:

    在当前版本的 DotVVM(0.8.6-pre)中,页面视图模型的 Context 属性由框架设置(在调用 Init 方法之前)。

    但是,如果 viewmodel 包含其他对象,则不会设置这些 Context(主要是因为性能原因 - 我们必须使用反射浏览 viewmodel 并分析每个属性)。

    目前,我建议将 Context 属性传递给 Init 阶段的子对象。

    public override Task Init()
    {
        LoginSection.Context = Context;
    }
    

    但是,在未来的版本中,我们计划添加一些机制来自动注入这些框架对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      • 2018-07-23
      相关资源
      最近更新 更多