C# | WPF Prism Screen Navigation Memory Release
How to release memory during C# WPF Prism screen navigation
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.
Related plants
More Tech articles →C# | How to call a MainWindow method from a partial View in WPF Prism
In WPF Prism, you can call a method on the Main Window from a partial view. Using Prism's Event Aggregator avoids direct references between view models and makes it easy to handle events raised within the application.
#csharp#wpf#prismC# | How to call a View method in ContentRegion from MainWindow in WPF Prism
In WPF Prism, an application may consist of a main window and a set of regions contained within it, hosting views and view models that communicate with each other. This explains how to call a method on a view or view model in the Content Region from the Main Window.
#csharp#wpf#prismC# | How to implement video (MediaElement) in WPF Prism using the MVVM pattern
How to implement video playback (MediaElement.Play()) in WPF Prism using the MVVM pattern.
#csharp#wpf#prism