Wednesday, October 17, 2012

How to reuse views in prism/mef

How to reuse views in prism/mef

Using Silverlight 5, Prism 4.1 and MEF.

I have a view, that is exported by its interface.

Sample:

[Export(typeof(IUploadListView)), PartCreationPolicy(CreationPolicy.NonShared)] public partial class UploadListView : RadWindow, IUploadListView { } 

I have a model (let say a main menu model), that want to reuse this view 2 times. Each instance of the view must be invoked and shown just once. I change the UploadType on the underlaying viewmodel, so that the behavior will change.

Sample:

var view = this.serviceLocator.GetInstance<IUploadListView>(); view.UploadListViewModel.UploadType = UploadType.MyType1; view.Show(); 

and the other menu option:

var view = this.serviceLocator.GetInstance<IUploadListView>(); view.UploadListViewModel.UploadType = UploadType.MyType2; view.Show(); 

The problem is this:

  • When using the NonShared policy I do get unique instances showable. The problem than is that the instance is shown twice (or more) when the user presses the same menu item.
  • When using the Shared policy, when the first view is shown, the 2nd menu item will reuse the 1st view, so only 1 view is shown.

What I want is that I must be able check if there is an instance of type IUploadListView shown, and when that happens, I just reuse the instance and call Show(). When there is no instance found, I want MEF to create it for me (with the service locator).

Is there a way to accomplish this ?

Answers & Comments...

Answer: 1

You should implement INavigationAware interface in your view or its view model and take advantage of the IsNavigationTarget method.

When RequestNavigate is called for a region, the IsNavigationTarget will be invoked to allow the instance of the view to decide whether it should be activated. If it returns true, the view will be activated. Otherwise Prism will create a new instance of the view, place it in the region and activate it.

See http://msdn.microsoft.com/en-us/library/gg430861(v=pandp.40).aspx for more details.

by : Zabavskyhttp://stackoverflow.com/users/1199711




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog