我应该在 Silverlight 项目中使用模型-视图-视图模型 (MVVM) 模式吗? [英] Should I use the Model-View-ViewModel (MVVM) pattern in Silverlight projects?

查看:23
本文介绍了我应该在 Silverlight 项目中使用模型-视图-视图模型 (MVVM) 模式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Silverlight 控件的一个挑战是,当属性绑定到代码时,它们在 Blend 中不再真正可编辑.例如,如果您有一个从数据馈送填充的 ListView,则在 Blend 中编辑该控件时将看不到任何元素.

One challenge with Silverlight controls is that when properties are bound to code, they're no longer really editable in Blend. For example, if you've got a ListView that's populated from a data feed, there are no elements visible when you edit the control in Blend.

我听说由 WPF 开发社区发起的 MVVM 模式也有助于保持 Silverlight 控件可混合".我仍然在思考它,但这里有一些解释:

I've heard that the MVVM pattern, originated by the WPF development community, can also help with keeping Silverlight controls "blendable". I'm still wrapping my head around it, but here are some explanations:

一个潜在的缺点是该模式需要额外的类,但不一定需要更多的代码(如上面的第二个链接所示).想法?

One potential downside is that the pattern requires additional classes, although not necessarily more code (as shown by the second link above). Thoughts?

推荐答案

我绝对认为您应该为 Silverlight 应用程序使用 MVVM 模式 - 该模式的好处之一是您实际上可以通过一些简单的技巧.我经常将可混合性"称为可设计性设计" - 您使用某些技术来确保您的应用程序在 Blend 中看起来很棒.

I definitely think you should use the MVVM pattern for Silverlight applications - and one of the benefits of the pattern is that you can actually make your application really blendable through some simple techniques. I often refer to "blendability" as "design for designability" - that you use certain techniques to make sure your application looks great in Blend.

其中一项技术(如 Torbjørn 指出的那样)是使用依赖项注入框架并根据代码是在 Blend 中还是在浏览器中执行来提供外部服务的不同实现.因此,当代码在 Blend 中执行时,我将我的容器配置为使用虚拟数据提供程序,这样您就可以获得对列表框、数据网格等的设计时支持.

One of the techniques - like Torbjørn points out - is to use a dependency injection framework and supply different implementations of your external services depending on wether the code is being executed in Blend or in the Browser. So I configure my container to use a dummy data provider when the code is executing in Blend, and that way you get design time support for your list boxes, data grids etc.

挑战通常是如何以声明方式设置 DataContext - 所以我经常最终使用服务定位器类作为 IoC 容器的前端".这样我就可以将数据上下文绑定到服务定位器上的一个属性.

The challenge is often how to set the DataContext declaratively - so I often end up using a service locator class a a "front end" to the IoC container. That way I can bind the data context to a property on the service locator.

另一种技术是创建某种具有两个属性的 ObjectDataSource 控件(非可视化):设计时数据上下文和运行时数据上下文.该控件负责检测正在执行的位置,然后将父 DataContext 设置为正确的对象.

Another technique is create some kind of ObjectDataSource control (non visual) that has two properties: Design Time DataContext and RunTime Data Context. The control does the job of detecting where is being executing, and then setting the Parent DataContext to the right object.

这篇关于我应该在 Silverlight 项目中使用模型-视图-视图模型 (MVVM) 模式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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