prismcag

In Composite WPF (Prism), what is the difference between IRegion.Add and IRegionManager.RegisterViewWithRegion?


In Composite WPF (Prism), when adding modules to the IRegionManger collection, what is the difference between using IRegion.Add and IRegionManager.RegisterViewWithRegion?

IRegion.Add

public void Initialize()
{
    _regionManager.Regions["MainRegion"].Add( new ModuleAView() );
}

IRegionManager.RegisterViewWithRegion

public void Initialize()
{
    _regionManager.RegisterViewWithRegion( "MainRegion", typeof( ModuleAView ) );
}

Solution

  • The difference is who is responsible for creating the view. In the IRegion.Add scenario (also called View Injection) you are responsible for instantiating the view beforehand. In the other scenario with RegisterViewWithRegion (also called View Discovery), the region manager instantiates the view itself.

    There are some technical reasons you would want to do one or the other. For example

    The relevant documenation is: For View Composition (including View Injection vs. View Discovery and discussions of View-First or View-Presenter-First approaches): http://msdn.microsoft.com/en-us/library/dd458944.aspx

    There's also a really handy "when to use each" section. Here's the excerpt from the docs:

    • Explicit or programmatic control over when a view is created and displayed, or when you need to remove a view from a region, for example, as a result of application logic.
    • To display multiple instances of the same views into a region, where each view instance is bound to different data.
    • To control which instance of a region a view is added (for example, if you want to add customer detail view to a specific customer detail region). Note that this scenario requires scoped regions described later in this topic.

    Hope this helps.