How to create a new view every time navigation occurs in PRISM?

Valentin V picture Valentin V · Feb 25, 2011 · Viewed 8.1k times · Source

I'm using WPF4 and PRISM4 for my new project.

There is a single module with several views in it. The DI is done with unity. When I navigate from ViewA to ViewB for the first time, the ViewB is created and its constructor is called. But when I try to navigate to ViewB for the second, third time, the ViewB is not created, but existing instance is reused.

I'm using IRegionManager.RequestNavigate for my navigation purposes.

I've tried to pass TransientLifeTimeManager to RegisterType Unity methods, but to no avail.

Is there a way to configure prism and/or unity to create a new view every time I navigate to it?

Thanks.

Answer

Jon picture Jon · Mar 4, 2011

The correct way to do this is by implementing INavigationAware either in your View or your ViewModel (Prism will check first the view, and if it doesn't implement INavigationAware it will also check the ViewModel).

You are interested specifically in the IsNavigationTarget method, which tells Prism if the current instance of the View should be reused, or if another instance should be created to satisfy the navigation request. So, to always create a new View you would do:

public class MyViewModel : INavigationAware {
    bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext)
    {
        return false;
    }

    void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext)
    {
    }

    void INavigationAware.OnNavigatedTo(NavigationContext navigationContext)
    {
    }
}

All of this is explained in greater detail in Chapter 8 of the Prism 4 documentation; they also have an illustration of how it works, which is very nice because it also lets you know exactly where you can hook in and how.