使用 PhoneApplicationPage 作为嵌套视图容器
在适用于 Windows Phone 的 MVVM Light 工具包中,每当我要添加新的 MvvmLightView (WP) 项目时,我最终都会使用为我创建 PhoneApplicationPage 的模板。
当我想创建嵌套视图时,例如在 ListBox ItemTemplate 视图的情况下,情况又如何呢?
在 MVVM Light 之前,每次我需要一个视图来分离标记时,我都会创建一个标准的 UserControl 并且效果很好。
创建可导航页面时我应该只使用 MvvmLightView 吗?
In MVVM Light toolkit for Windows Phone, whenever I am to add a new MvvmLightView (WP) item, I end up with the template creating a PhoneApplicationPage for me.
What about cases, when I want to create a nested view, for example in case of a ListBox ItemTemplate view.
Before MVVM Light, every time I needed a view to separate markup to, I would have created a standard UserControl and that worked fine.
Should I only use MvvmLightView whenever creating a navigable pages?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
项目模板是一个指南,它为您生成一些代码。 它不是、也不打算成为创建视图或子视图的单一方式。
在您提到的情况下,通常创建一个支持其自己的视图模型的用户控件。然后,该子视图视图模型将作为属性包含在主视图模型中。要将其传递给子视图(例如用户控件),请将此属性绑定到用户控件的 DataContext。
但是,您不需要需要单独的视图模型,在某些情况下共享主视图模型更合适。在这种情况下,您不需要执行上述绑定,因为它是隐式执行的。此外,当您在 DataTemplate 中使用用户控件时,模板 DataContext 会隐式传递给用户控件,并且您不需要绑定。一般来说,只有当您想要绑定到当前上下文的属性或另一个上下文时,才需要设置数据上下文。
MVVM 是关于自由的,而 MVVM Light 是关于支持开发人员使用这种自由的。所有指南都是最佳实践,通常提供最简单和/或最一致的方法,但没有什么可以阻止您有充分的理由走另一条路。特别是,模板只是为一个问题提供的快捷方式,而不是针对一般(意味着每种)情况。
The item template is a guidance, that produces some code for you. It is not, nor does it intend to be, the single way of creating views or sub views.
In the case you are mentioning, it is usual to create a user control hat is backed on its own view model. This sub-view view model is then included as a property in your main view model. To pass it to your sub-view (e.g. a user control) you bind this property to the user control's DataContext.
However, you do not need a separate view model, in some cases it is more appropriate to share the main view model. In this case you do not need to do the above binding, as it is do one implicitly. Also, when you are using the user control within an DataTemplate the templates DataContext is passed to the user control implicitly and you do not need the binding. In general you only need to set the data context when you want to bind to a property of the current context, or to another context.
MVVM is about freedom and MVVM Light about supporting the developer in using this freedom. All guidance are best practises and provide usually the easiest an/or most consistant way, but nothing stops you going down another route for a good reason. Especially the templates are just shortcuts that provide for one problem, but not for the general (meaning every) case.