Benefits of View/ViewModel Re-use

Topics: Prism v4 - WPF 4
Jun 28, 2012 at 5:41 AM

Hi all,

I am creating my first non-trivial Prism-based WPF app and generally I am quite liking it.

The kind of apps I work on are generally touch-screen Kiosk based applications which may not be exactly what Prism is geared towards but I have one question I would like some advice on.

I was quite confused when I got a null reference exception in one of my view models. Turned out that a resource I create on my constructor was null. A little further investigation lead me to the discovery that my view (and subsequently viewmodel) was only created the first time.

Turns out this is a feature of Prism and if I Implement INavigationAware I can revert this behaviour so that a new instance is created each time. All well and good - just set my base usercontrol/viewmodel to IsNavigationTarget=false.

My question is - am I doing it wrong doing it like this. if I want my application to create a new viewmodel each time the view is loaded am I missing a fundamental part of Prism?

For me not-sharing these makes it much easier to develop and manage resources etc. on my view models (which are the main repository of code in my app) as the lifecycle of the object and this is associated properties is quite clear.

I understand re-using the view/model will be 'faster' but I doubt it would make much difference really - is this singleton approach perhaps designed to alleviate the common issues of memory leaking etc in WPF apps?

What are people's thoughts on this matter?

cheers,

Robert

Developer
Jun 28, 2012 at 6:34 PM

Hi Robert,

As far as I know, this is a normal behavior in Prism. When using view-based navigation, you might have an scenario where you want to navigate to an existing view in the region or to a new instance of a view. In order to support both scenarios, Prism defines the INavigationAware which provides the IsNavigationTarget method.

Although Prism's default behavior is to navigate to existing views in the region, as far as I know, this is not associated with any specific "aspects" like performance or memory leaks. What is more, implementing the INavigationAware interface and its IsNavigationTarget method is a common approach in Prism.

However, take into account that, when performing a navigation request, Prism does not remove the previous view from the region by default, it only deactivates it. Thus, your previous used views wouldn't be disposed and garbage collected by default. In order to change this default behavior, you can implement the IRegionMemberLifetime interface in your views or view models and set its KeepAlive property to false. Doing so, the views / view models will be removed from the region when deactivated.

You can find more information about this in the following chapter of the Prism documentation:

I hope you find this useful,

Damian Cherubini
http://blogs.southworks.net/dcherubini