用于添加新实体的 MVVM WPF ViewModel [英] MVVM WPF ViewModels for Adding New Entity

查看:46
本文介绍了用于添加新实体的 MVVM WPF ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 WPF 中的 MVVM 的概念是我们为您的应用程序中的每个模型都有一个 ViewModel.这意味着如果我们有 Customer 类(实体),那么我们将有 CustomerViewModel.CustomerViewModel 将拥有代表客户所需的所有属性.CustomerView 用户控件将负责为 Customer 模型创建 UI.

My concept for MVVM in WPF is that we have a ViewModel for every Model in your application. This means that if we have Customer class (entity) then we will have CustomerViewModel. The CustomerViewModel will have all the properties which are necessary to represent a customer. The CustomerView usercontrol will be responsible for creating the UI for the Customer model.

现在,假设我们要添加一个新客户.所以,我们有一个由 FirstName、LastName 等组成的表单.对于这个场景,我们是否需要一个 ViewModel.我的意思是我所要做的就是从 TextBox 获取所有输入值并创建一个 Customer 对象,然后将其保存到数据库中.为什么我要为这个场景创建一个 ViewModel?

Now, let's say that we are adding a new customer. So, we have a form which consists of FirstName, LastName etc. Do we need a ViewModel for this scenario. I mean all I have to do is to take all the input values from TextBox and create a Customer object and then save it to the database. Why should I bother creating a ViewModel for this scenario?

推荐答案

首先,这不是 MVVM 的主要目的,镜像"一切.视图应该提供用户输入的方法,当然不处理对任何数据库层的调用.ViewModel 应该是一个与 GUI 无关的应用程序主干,它肯定应该处理客户的创建.

First of all, that is not the main purpose of MVVM, to "mirror" everything. The View should provide the means for a user input, and certainly not process calls to any of the database layers. The ViewModel should be a GUI-agnostic application backbone, and it definetly should handle the creating of customers.

也就是说,您应该做的是拥有一个代表处理客户的工作区的 ViewModel,而不仅仅是客户 ViewModel.如果您真的想节省正在创建的几个对象,请向该工作区添加创建和添加新客户(而不是 CustomerViewModel)的可能性.这样,您可以拥有工作区的视图,其中包含客户的每个相关/必需属性的元素,并且通过调用添加到该工作区 ViewModel 的某些命令,您可以获得填充这些(绑定到 ViewModel 的数据)的当前值直接在客户模型中查看元素.

That said, what you should do, is have a ViewModel which represents a workspace for handling customers, and not just a customer ViewModel. If you really want to save on a few objects being created, add to that workspace the possibility to create and add a new customer (not CustomerViewModel). That way, you can have a View of the workspace which has elements for each relevant/required property of the customer, and by invoking some command added to that workspace ViewModel, you could get the current values filled in those (data bound to ViewModel) View elements directly to the customer model.

考虑一下,如果您稍微重构一下,是否可以删除特定客户(和其他模型)的 ViewModel,最好避免在没有明确原因的情况下盲目地遵循某种模式.

Consider if you could probably drop the specific customer (and other Model) ViewModels if you refactor things a bit, it would be good practice to keep things from adhering blindly to a certain pattern without explicit cause.

这篇关于用于添加新实体的 MVVM WPF ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆