gpt4 book ai didi

c# - MVVM——模型的正确实现

转载 作者:行者123 更新时间:2023-11-30 21:58:27 32 4
gpt4 key购买 nike

背景:
C#/WPF Windows-Store 应用程序使用 SQLite 在本地存储数据,并通过 Web 访问下载数据。

应用:
数据必须从网上下载并映射到一个存储在本地 SQLite 数据库中的类。例如,在客户类中:

[Table("Customer")]
class Customer{
[AutoIncrement, PrimaryKey, Unique]
public int Id {get;set;}
public string Name {get; set;}

}

该类由不同的线程操作,因此 Customer 类中的 INotifypropertyChanged 不是一个好主意。此外,GUI 应显示多个客户,因此 ViewModel 包含一个客户列表。此外,客户必须通过多个属性进行扩展才能由 GUI 正确显示。

问题:
什么是模型?客户?
我应该如何在不弄乱 Customer 类的情况下使用其他属性扩展 Customer ?
除了将客户存储在数据库中或从 Web 下载数据并将其映射到客户类的业务逻辑之外,我应该在哪里?在模型中?
如果您的答案是客户就是模型并且它不应该包含任何逻辑,那么为什么 MVVM 模式说模型包含业务逻辑?

最佳答案

在这种情况下,客户肯定是模型。模型应该是 POCO并且每个仅由 GUI 使用的属性都应该在 View 模型中,例如 CustomerViewModel。

业务逻辑应该在一个模型中。可以通过使用 repository pattern 来解决存储在数据库中的问题.

模型通常有逻辑,但仅限于业务逻辑。根据 MVVM,您不应将任何 UI 逻辑放在模型中,而应放在 View 模型中。

假设我们有您的模型

class Customer {
public int Id { get; set; }
public string Name { get; set; }
}

并且需要以大写形式显示客户姓名。不是向 Customer 类添加额外的属性,而是在 View 模型中添加一个

class CustomerViewModel implements INotifyPropertyChanged  {
...
public string UpperCaseName { ... }
...
}

我认为 Wikipedia page总结得很好:

Model

Model refers either to a domain model, which represents the real state content (an object-oriented approach), or to the data access layer that represents that content (a data-centric approach).

View

As in the MVC and MVP patterns, the view is the user interface (UI).

View model

The view model is an abstraction of the view that exposes public properties and commands. Instead of the controller of the MVC pattern, or the presenter of the MVP pattern, MVVM has a binder. In the view model, this binder mediates communication between the view and the data binder. The view model has been described as a state of the data in the model.

Binder

Declarative data- and command-binding are implicit in the MVVM pattern. In the Microsoft solution stack, the binder is a markup language called XAML. The binder frees the developer from being obliged to write boiler-plate logic to synchronise the view model and view. When implemented outside of the Microsoft stack the presence of a declarative databinding technology is a key enabler of the pattern.

关于c# - MVVM——模型的正确实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30087568/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com