【问题标题】:Is it right for a ViewModel to inject itself into its child ViewModels?ViewModel 将自己注入其子 ViewModel 是否正确?
【发布时间】:2009-06-23 07:39:14
【问题描述】:

我创建了一个MVVM test application,它在运行时读取 XML 文件以动态创建菜单并根据用户选择的内容动态加载该页面的 UserControl。结果是一个很好的 MVVM 模式,它允许您在一个 XML 文件中定义每页一个 View/ViewModel 对。很不错。

所以现在我只是为开发人员添加了在一个页面上创建一个可以转到另一个页面的按钮的功能。我这样做的方法是在 MainViewModel 我在 ObservableCollection 中构建 ViewModel 的集合,当我构建每个时,我 将 MainViewModel 本身(this)注入到每个 UserControl-ViewModel 的构造函数中强>。这样每个 UserControl 内部都有 MainViewModel,以便开发人员可以通过 MainViewModel 操作应用程序(例如调用 SwitchPage(idCode))。

我需要保存的任何全局状态都可以保存在每个 UserControl 都可以访问的 MainViewModel 中。

此外,每个 UserControl (PageItem) 都具有对其他每个 UserControls 的完全访问权限,这使我基本上可以从任何 UserControl 控制应用程序中的任何内容,这是我一直试图在MVVM应用很久了。

所以我的问题是:这种 ViewModel 注入是一种有用/已知的模式,还是将 ViewModel 注入其子 ViewModel 是否存在问题?这对我来说似乎是递归的,但似乎工作正常并且给了我到目前为止我想要的功能。根据我从复合应用程序库架构中学到的知识,这似乎与那里正在发生的事情相似,例如在下面的代码中,我可以根据需要将其他应用程序对象注入到我的 ViewModel 中。

public MainViewModel()
{

    PageItems pageItems = PageItems.Create("all");

    foreach (PageItem pageItem in pageItems.Collection)
    {
        string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
        string viewModelName = assemblyName + ".ViewModels.PageItem" + StringHelpers.ForcePascalNotation(pageItem.IdCode) + "ViewModel";
        var type = Type.GetType(viewModelName);
        var viewModel = Activator.CreateInstance(type, this, pageItem) as ViewModelPageItemBase;
        AllPageItemViewModels.Add(viewModel);
    }

    CurrentPageItemViewModelIndex = 0;
    LoadCurrentPageItemViewModel();
}

【问题讨论】:

    标签: wpf mvvm application-design


    【解决方案1】:

    我不认为这是对或错,但更多的是关于你的设计是如何耦合的。我通常从您提到的方法开始(子虚拟机引用父虚拟机),然后如果我发现它变得太笨重,就解耦。您的第一个选择不一定是您的最后一个选择 - 您可以随着代码的发展重构代码。

    可能的替代方案是:

    • 子虚拟机引发父监听的事件(观察者模式)。 Parent VM 非常了解孩子,但孩子不了解父母。
    • 子 VM 在事件中心上发布事件,父级侦听(调解器模式)。孩子和父母都没有密切了解彼此。他们只知道调解员。

    【讨论】:

      猜你喜欢
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多