问题
I have an existing Silverlight 4 application that I am attempting to convert to use the locator pattern and the MVVM-Light library.
My understanding is that the MvvmLocator class keeps a reference to each view model and allows you to bind the DataContext of each view to an appropriate ViewModel in the locator.
My application uses a navigation frame and hence each page in the app is a UserControl that gets loaded into the Content frame.
I can see how easy it is to bind each page view to the appropriate ViewModel in the locator, but my problem is that I have other UserControls with their own view models that get re-used in multiple contexts and it would cause problems if each instance of the control got bound to the same ultimate view model instance.
For example, I have a search page that consists of 2 user controls. The first is a search parameter control that contains several inter-dependent combo boxes and a search button. The second is the results grid itself. The view model of the page that contains these 2 controls handles the communication between them. The problem is that this search control gets used on other pages as well, and having them all use the same view model instance would cause all kinds of headaches. So, using the normal "DataContext={Binding ProductSearch, Source={StaticResource Locator}}" seems out of the question...
Has anyone else run into this or have any bright ideas how to solve it? I'm thinking maybe I could modify the locator to create a new instance of the view model for each page where the control is used. Otherwise, I could just force a cleanup on every page transition, but then I wouldn't be able to save state between pages.
I am new to the whole Silverlight and MVVM world, so maybe I am missing something about how this all should be structured or have painted myself into a corner. I'm just not sure. I would definitely welcome any suggestions.
回答1:
Your main problem is the fact that the Silverlight navigation framework always creates a new instance of a view when you navigate to it. You can override this behavior using INavigationContentLoader and storing instances of your views to be re-used.
Some examples of using INavigationContentLoader are David Poll's Opening up Silverlight 4 Navigation: Introduction to INavigationContentLoader or Mike Taultry's Silverlight 4 Rough Notes: Taking Control of Navigation blog posts. These posts only show how to create your own content loader; using it to reload existing views is up to you.
来源:https://stackoverflow.com/questions/3097865/mvvm-light-locator-pattern-and-reusable-usercontrol