2

I have written a phone app using an MVVM framework. It came together okay - every page (view) on the phone has its own ViewModel and code within each ViewModel went away to the dataservice and retrieved appropriate data.

So I had a page showing an Agenda of upcoming items and its ViewModel retrieved a collection of events and within the XAML I bound a Listbox to this collection. Similarly I had another page showing a OneOff Events and again, within its VM I called the data service to get a collection of data back and that was bound to a listbox within its view.

Not sure how good an implementation of MVVM this is, but, I ended up moving to a different database - and it was very easy to implement another dataservice without touching anything else and it all worked great.

Ok - so now I am looking to rework this app into a Windows Store app. I now have a main page that will show a combination of data that on the phone was shown on individual pages. Hypothetically, assume that the Agenda items and One Off Events mentioned above are now appearing on the same main page (so much more room to show stuff)

Just struggling with what this means for ViewModel(s). If the MainPage can only work with one ViewModel, do I end up with one huge ViewModel that includes all the functionality that was in multiple VM's before.

Or should the Main ViewModel have within it collections of ViewModels. From looking around this seems to be the way it could be done, but, if so where are the ViewModels created? It seems quite a fundamental shift from what I have done previously.

4

1 回答 1

1

是的,您可以将不同的 ViewModel 设置为页面不同部分的绑定上下文。您可以使用定位器模式(一个具有 ViewModel 属性的定位器对象)或依赖注入来保持事物的构造可管理。

Gill Cleeren 的精彩示例代码和幻灯片讨论并展示了如何使用 MVVM 交替设置Contoso Cookbook 示例应用程序,可以在此处找到 ViewModelLocator 类。谈话本身在第 9 频道

从这些幻灯片中:

数据绑定是粘合剂,但......

视图需要“找到”它的 ViewModel

  • ViewModel 是 DataContext

可以是静态的或动态的

  • 静态:View 创建 ViewModel 并将其设置为 DataContext

  • 动态:在运行时,View 选择它的 ViewModel,反之亦然

    2个选项:

    • View-First:创建 ViewModel 是因为创建了 View
    • ViewModel-First:创建 ViewModel 并选择 View
于 2013-04-21T00:27:19.280 回答