Nested Regions - Region not found

Topics: Prism v4 - WPF 4
Mar 30, 2012 at 12:16 AM
Edited Mar 30, 2012 at 12:17 AM

I have the following Region hirerachy

MainRegion

-----SubMainRegion

-------------RegionA

-------------RegionB

I use ViewModel first approach and then lookup for view corresponding to that ViewModel.

I try to load SubMainRegion from MainRegionViewModel. Then in the constructor of SubMainRegionViewModel I try to load views in RegionA and RegionB. The problem is that when I try to add view to either SubMainRegion, RegionA or RegionB, I get the "Region Not Found" error. It seems that these regions (SubMainRegion, RegionA and RegionB) doesn't get registered since they are nested within the MainRegion and not directly defined in the MainRegion.xaml. What could be done so that the SubMainRegion, RegionA and RegionB are eagerly registered? Also is this approach reasonable?

 

regards,

Nirvan.

Developer
Mar 30, 2012 at 5:42 PM

Hi,

Based on my understanding of your scenario this error could be happening due to a timing issue, as the DelayedRegionCreationBehavior will create a new region when the control that will host the region is added to the VisualTree. Hence, when using ViewModel first approach like in your case, your new region won't be available when you try adding the inner views in your ViewModel's constructor as the corresponding view has not yet been added to the VisualTree.

As far as I know, to avoid this kind of errors you could try using the View Discovery approach to register your views from inside your ViewModel's constructor. This way when a region is created, the region looks for all the ViewTypes associated with the region and automatically instantiates and loads the corresponding views.

You could find more information about this in the following chapter of the Prism documentation at MSDN:

As another option, you could add the inner views once you ensure the region has been added to the VisualTree. For example in your view model you could subscribe to the Loaded event of the view and add the corresponding inner views in its handler method.

I hope you find this handy,

Agustin Adami
http://blogs.southworks.net/aadami


Mar 30, 2012 at 6:46 PM

I deal with this scenario a lot.

I personally use events and ViewInjection to tell when a parent view is injected, meaning the child region should be visible, which means it is safe to inject the child view.

I also inject all views using scoped region managers.  This prevents any future problems of having multiple regions/views of the same name conflicting in the same region manager (ie. it's not allowed).

I would however use ViewDiscovery if this was all done at startup, since it would all happen during the CreateShell method, which as far as I can tell must complete its cycle before any events can be subscribed to.