I have an application that shows one view at a time in ContentControl. I have a current solution, but I was curious if there is a better one for memory management.
My current project creates new objects when they need to be displayed, and destroys them when they are no longer visible. I am wondering if this is a better approach or is it better to maintain links to each view and replace those links?
Here are a few more explanations of my application layout:
A very simplified version of my MainWindow.xaml looks like this:
<Window ... > <Window.Resources> <DataTemplate DataType="{x:Type vm:SplashViewModel}"> <view:SplashView /> </DataTemplate> <DataTemplate DataType="{x:Type vm:MediaPlayerViewModel}"> <view:MediaPlayerView /> </DataTemplate> </Window.Resources> <Grid> <ContentControl Content="{Binding ActiveModule}" /> </Grid> </Window>
In my MainViewModel.cs, I am changing the ActiveModule parameter to the new initialized ViewModels. For example, my logical check for pseudocode for content sharing would look something like this:
if (logicCheck == "SlideShow") ActiveModule = new SlideShowViewModel(); else if (logicCheck == "MediaPlayer") ActiveModule = new MediaPlayerViewModel(); else ActiveModule = new SplashScreenViewModel();
But will it just keep the link more suitable for speed and memory usage?
Alt Option 1. Create static links to each ViewModel and replace them ...
private static ViewModelBase _slideShow = new SlideShowViewModel(); private static ViewModelBase _mediaPlayer = new MediaPlayerViewModel(); private static ViewModelBase _splashView = new SplashScreenViewModel(); private void SwitchModule(string logicCheck) { if (logicCheck == "SlideShow") ActiveModule = _slideShow; else if (logicCheck == "MediaPlayer") ActiveModule = _mediaPlayer; else ActiveModule = _splashView; }
I don't constantly create / destroy here, but this approach seems wasteful to memory when unused modules just hang out. Or ... is there something special WPF is doing behind the scenes to avoid this?
Alt Option 2: put each available module in XAML and show / hide it:
<Window ... > <Grid> <view:SplashScreenView Visibility="Visible" /> <view:MediaPlayerView Visibility="Collapsed" /> <view:SlideShowView Visibility="Collapsed" /> </Grid> </Window>
Again, I wonder what kind of memory management can happen in the background, which I am not familiar with. When I destroy something, it completely goes into some kind of hibernation? I read that some things (without cheating, events, key inputs, focus, ...), but what about animation and other things?
Thanks for any input!