1

假设我有一个场景,我想要显示一个由许多其他业务对象组成的业务对象,即它是深度分层的。

为了显示数据,我想使用 masterDetail 类型的视图,但有很多层次让我可以越来越深入地挖掘数据。

所以我想从对象根目录的某个列表中选择一个项目,并显示其属性的详细视图,然后从该详细视图中选择一个项目并显示其详细视图等。

如果我不与数据交互,那么我不需要为深层层次结构中的每个模型创建 viewModel,因为我可以直接绑定到模型。

如果我正在与数据交互,那么我可能想用视图模型包装整个业务对象及其后代,并绑定到它,允许我添加命令来执行某些逻辑。

但是,如果我只想与特定级别的数据交互怎么办?尝试直接从 XAML 或 codeBehind 与模型交互会很麻烦。然而,用 ViewModels 包装整个事情需要做很多工作。

我想我只会使用转换器在特定点创建视图模型

<DisplayControl DataContext="{Binding A}">
   <DisplayControl DataContext="{Binding B}">
      <InteractionControl DataContext="{Binding C, Converter{ConvertModelToViewModel}}">
      </InteractionControl >
   </DisplayControl >
</DisplayControl >

但是如果我需要对这些 Viewmodel 执行清理呢?例如从事件中注销。每次我来回访问同一个项目时,它都会为同一个模型创建新的视图模型。我不想依赖垃圾收集,因为根据他们正在做的事情,保留视图模型可能会很昂贵,而且 GC 甚至可能不会发生(例如,如果我注册到静态类的事件)。使用弱事件对 GC 会有所帮助,但对于将昂贵的 viewModel 保留得比他们需要的时间更长的情况,它仍然无济于事。

4

1 回答 1

1

It is not easy to give a general answer to this question as it refers to the architecture of an MVVM application and there are many aspects to consider. It probably helps to sort the decisions to make and provide a couple of best practices. An answer to this will always be opinionated as it involves matters of style and taste...

A real life, complex MVVM application cannot be built without a fair bit of infrastructure which is often ignored by the tutorials. Especially for the construction of views, ViewModels and models as well as for glueing everything together there are many concepts available.

I will just give you an idea of how I have dealt with the problems you mention:

I never bind to models directly. ViewModels tend to become more complex as the application grows and the ViewModels which don't contain any additional logical aspects (compared to the model) are really, really few. Change notification (INotifyPropertyChanged) is another aspect: It makes sense to isolate this aspect to the ViewModel, as long as the change notification is required for UI purposes only. I recommend spending the extra effort for the sake of maintainability and scalability. You don't want to be forced into a major redsign just because you forgot something at the beginning.

Implement infrastructure to deal with common MVVM tasks, like synchronizing a collection on a ViewModel with a collection on a view. See the answer here for details. I ended up building a ViewModelFactory which deals with construction and caching of ViewModels. This even allows recycling of ViewModels (take a ViewModel instance that is not needed any more and just switch the model, similar concept to UI virtualization in recycling mode).

Of course, this is not a full answer to your question but I hope it helps you to go further. If you've got more specific questions, feel free to get back to me.

于 2013-11-15T07:17:42.740 回答