简体   繁体   English

在ASP.NET MVC和WPF MVVM中重用相同的模型

[英]Reuse the same models in ASP.NET MVC and WPF MVVM

I'm developing an application in WPF MVVM, but I'll also need to create an MVC project in the same solution. 我正在WPF MVVM中开发一个应用程序,但我还需要在同一个解决方案中创建一个MVC项目。

I would like to know if there is any way to reuse the same Models in both classes, and the best way to do it, since to meet the MVVM specifications 我想知道是否有任何方法可以在两个类中重用相同的模型,并且是最好的方法,因为要满足MVVM规范

For example, I need to add a "PropertyChanged" to the set of my properties, something unnecessary in MVC project. 例如,我需要在我的属性集中添加一个“PropertyChanged”,这在MVC项目中是不必要的。

I agree with @@Douglas Gandini. 我同意@@ Douglas Gandini。 You should define your business objects in a separate assembly that you can reference from both your ASP.NET and WPF applications. 您应该在可以从ASP.NET和WPF应用程序引用的单独程序集中定义业务对象。 These classes should not implement any client-specific interfaces such as INotifyPropertyChanged but be pure POCO classes that contains business logic only. 这些类不应实现任何特定于客户机的接口,如INotifyPropertyChanged,而应是仅包含业务逻辑的纯POCO类。

In your WPF application, you could then create a view model class that implements the INotifyPropertyChanged interface and wraps any properties of the business object that it makes sense to expose to and bind to from the view. 在WPF应用程序中,您可以创建一个实现INotifyPropertyChanged接口的视图模型类,并包装业务对象的任何属性,以便从视图中公开和绑定。

The view model then has a reference to the model, ie your business object that is defined in a separate assembly that may be shared between several different client applications, and the view binds to the view model. 然后,视图模型具有对模型的引用,即您的业务对象在可以在多个不同客户端应用程序之间共享的单独程序集中定义,并且视图绑定到视图模型。 This is typically how the MVVM design pattern is (or should be) implemented in a WPF application. 这通常是在WPF应用程序中(或应该)实现MVVM设计模式的方式。 The view model class contains your application logic , for example how to notify the view when a data bound property value is changed, and the model contains the business logic that is the same across all platforms and applications. 视图模型类包含应用程序逻辑 ,例如,如何在更改数据绑定属性值时通知视图,并且模型包含所有平台和应用程序中相同的业务逻辑。

Of course this means that you will end up with a larger number of classes in total but this is not necessarily a bad thing as each class has its own responsibility. 当然,这意味着你最终会得到更多的课程,但这不一定是坏事,因为每个班级都有自己的责任。 The responsibility of a view model is to act as a model for the application specific XAML view whereas the responsibility of the model class is to implement the business logic. 视图模型的职责是充当特定于应用程序的XAML视图的模型,而模型类的职责是实现业务逻辑。

Create a shared assembly. 创建共享程序集。 Call it Contracts or Models and share it between your WPF and MVC 将其称为合同或模型,并在WPF和MVC之间共享

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM