C# | WPF Prism Screen Navigation Memory Release

How to release memory during C# WPF Prism screen navigation

TechPublished 1 min read

In WPF Prism, screen navigation happens through a feature called Region.

For navigation-based screen transitions (where the Region part that makes up part of the screen switches), you implement the INavigationAware interface on the destination.

The IsNavigationTarget method that this generates decides, via its bool return value, whether to reuse the ViewModel instance — but even returning false doesn't release the memory.

【Return value of IsNavigationTarget】

  • true: Reuse the instance. The constructor isn't called the next time the screen is launched.
  • false: Don't reuse the instance. The constructor is called the next time the screen is launched. However, the memory is not released.

How to release memory on navigation-based screen transitions

Implement the IRegionMemberLifetime interface on the ViewModel, and set the KeepAlive property to false.

Also, if you're implementing the INavigationAware interface alongside it, set IsNavigationTarget to True.

Here's an example implementation on a ViewModel.

▼SampleViewModel.cs

public class SampleViewModel : BindableBase, INavigationAware, IRegionMemberLifetime
{
    /// <summary>
    /// ViewModel破棄に伴いメモリ開放する際はfalse
    /// </summary>
    public bool KeepAlive { get; set; } = false;

    public SampleViewModel()
    {
    }

    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        //// RegionMemberLifetime(KeepAlive = false)でViewModelを破棄するため、こちらはTrue
        return true;
    }

    public virtual void OnNavigatedFrom(NavigationContext navigationContext)
    {
    }

    public virtual void OnNavigatedTo(NavigationContext navigationContext)
    {
    }
}

That's it.