开发者

How to control instantiation of View and ViewModel in Silverlight?

My silverlight application has 2 pages, PageA and PageB. Each page is binding to it corresponding ViewModel, PageAViewModel and PageBViewModel. (I set ViewModel to View's DataContext inside xaml.)

User can switch back and forth between these pages, when user switch between these pages they create new instance of PageA and PageB which also create new object of its ViewModel which I don't want. I try to set NavigationCacheMode to Enable, now all Views create instance only first time user navigate to that page this also mean ViewModel has only one instance.

I want to know how to control UI to create only one instance of View and control when to create new instance of its ViewMod开发者_如何学Goel?


This is where IOC (Inversion Of Control), like Unity, comes in handy.

You would simply register the ViewModel as a singleton (one only, ever) with Unity.

Rather than embed a ViewModel in the View (really bad practice to hardwire them like that ), you specify what type of ViewModel the View wants when it is created and the matching ViewModel would be "injected" into the view.

Basic MVVM, without some other injection framework, does not give you much out of the box (aside from a separation from the view).


Have you tried using MVVM light framework for your application. It supports a view model locator concept which avoids recreating the instance of your VM each time a user clicks on a page. Take a look at a presentation by Laurent Bugnion here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜