Ivan Krivyakov's Blog

Premature optimization is the root of all evil

May 22, 2012

Prism Region Manager and Data Templates

When you add a view to a region (Region.Add(view)), it could be a real view, or a data template from which the view is created. The region tries to associate current region manager with the view by setting the IRegionManager.RegionManager property on it. This is useful if the view has its own regions, and this is crucial if the view is a root of new region scope.

To do so, they cast the view to DepenencyObject and if the cast is successful, set the property. When some regions are found in the view or its children, Prism will walk up the logical tree to find the region manager. This will work fine if the view is the real view, but it will break miserably if the “view” is a data object and the real view is created from data template / content presenter.

Prism Region Manager and ContentPresenter

Very brief note, so I don’t forget the circumstances: I may write a sample later. When you define Prism region in your view like this:

<igDock:TabGroupPane prism:RegionManager.RegionName="SomeRegion" />

Prism has two-staged process that brings your region to existance. First it needs to create a Region object, this is done by DelayedRegionCreationBehavior. Then it attaches your region to a region manager in RegionManagerRegistrationBehavior. The $1M question is: what region manager? To answer that, Prism walks up the logical tree to find a parent view with an already attached region manager (e.g. the shell).

The trouble is, if there is a ContentPresenter in the way, it won’t work. Experiment shows that ContentPresenter adds its child to the visual tree, but not to the logical tree. See also here. So, the region manager instance won’t be found, and the region object will be created, but not added to any region manager.

The program will continue without error until you actually try to access that region.