MVVM - View 模型/模型绑定(bind)

标签 mvvm model viewmodel

我对使用父子模型关系的 MVVM 最佳实践有哪些疑问。

在这种特定情况下,有两个模型(数据类),称为组和联系人。该组包含一个联系人列表。它们都在实现 INotifyPropertyChanged 接口(interface)。

在 View 中,有一个使用 DataTemplate 显示层次结构的 TreeView ,关联的 ViewModel 包含一个 ObservableCollections 属性。

我想知道在这种情况下最佳实践设计是什么......在绑定(bind)到 xaml 的 ViewModel 中拥有一个像上面这样的属性,或者为每个模型(如 GroupViewModel 和 ContactViewModel)创建一个 ViewModel 而不是 ObservableCollections有一个列表。

什么是最好的方式(设计明智)?我应该将 Model 还是 ViewModel 绑定(bind)到 xaml?

最佳答案

恐怕,您混淆了一些东西。 MVVM 的基础是

  • 模型 - 包含应用程序正在使用的数据。它应该尽可能简单。
  • ViewModel - 反射(reflect)应用程序的状态并包含业务逻辑。这是业务层。
  • View - 解释 ViewModel 以提供业务层及其状态的可视化表示。

有了这三个部分,就可以很容易地提供关注点分离和解耦架构。如果您想阅读更多,click here .

回到你的问题:

In that specific case there are two models (data classes) called Group and Contact. The group is containing a list of contacts. Both of them are are implementing INotifyPropertyChanged interface.

这有点奇怪。通常,您不需要实现 INotifyPropertyChanged在模型类中,因为 VM 应该处理来自 View 的值更改。

但可以想象在模型层中也具有该机制。但是由于您不想跟踪这一层上的更改,恕我直言,VM 应该关心,所以您不需要它。

[...] Having one property like above in the ViewModel which is bind to the xaml or createing a ViewModel for each model (like GroupViewModel and ContactViewModel) [...]

是的,这通常是方法。对于应传递给 View 层的每个模型类,您将创建一个 ViewModel。 .

[...] and instead of ObservableCollections having an List.

这绝对是一个编号。如果您使用 List<T> , View 不会知道集合的更改(添加、删除)。

What is the best way (design wise)? Shoudl I bind the Model or the ViewModel to the xaml?

只需坚持使用 MVVM。 View 知道 VM,但 VM 不知道 View 。此外,VM 知道模型,但模型不知道。这意味着,您应该始终将 VM 绑定(bind)到 View 。

编辑

以下是完全合法的。

public class Address : ViewModelBase // implements INotifiedPropertyChanged a.s.o.
{
    public string Street { /* you know what comes here */ }
    public string ZipCode { /* ... */ }
    public string City { /* ... */ }

    /* more properties */
}

public class Person : ViewModelBase 
{
    public string Name { /* ... */ }

    public Address Address { /* ... */ }
}

关于MVVM - View 模型/模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17166092/

相关文章:

java - Android Room-插入之前如何检查同名实体?

c# - MVVM 模式,ViewModel DataContext 问题

ruby-on-rails - Rails 4 模型子文件夹

model - 使用 Automapper 将大领域模型映射到数据库对象

silverlight - MVVM : how to pass parameter to ViewModel's constructor

c# - HierachicalDataTemplate 和带有 ItemsControl 的 DataTemplate 之间的区别

c# - MVVM:处理非常大的 View 模型

php - 如何使用mySQL添加 'A' ,'B' ,'C'这样的分数

java - 刚刚创建后更新注释

Android 数据绑定(bind)和 View 模型不工作