How do I "pre-load" a view model
I would like to Preload a WPF ViewModel While Showing a Loading Overlay.
I'm working on a WPF application using the MVVM pattern. I have a
ViewSelector
property that switches between views based on its value. I also have a loading overlay (ViewSelector = 4
) that I want to display while a ViewModel is being preloaded.
Here’s the problem: One of my views (ViewSelector = 1
) takes a long time to initialize because it loads a lot of data and performs heavy processing. I want to:
Show the loading overlay (ViewSelector = 4
) while this ViewModel is being prepared.
Load the heavy ViewModel in the background to keep the UI responsive.
Automatically switch to the target view (ViewSelector = 1
) when the background preparation is complete.
Here’s my current approach in the ViewModel's command:
This works but causes an issue because switching to ViewSelector = 1
itself involves heavy operations that block the UI if done synchronously. I’ve considered using BackgroundWorker
or other threading mechanisms but ran into problems with updating ViewSelector
on the wrong thread.4 Replies
Here’s the relevant XAML snippet for context:
I’d appreciate any suggestions or best practices on how to structure this properly! Thanks in advance.
A view model is nothing special. It's just a class that implements INPC and you can reference it as the datacontext in a control. If you want to preload it, you can just create an instance and bind it in the control at a layer point.
So in your case, an example is using DI and creating the instance in the main collection before the app starts. Then just reference it when the control loads.
There's no real build in system for it. You can just write code that sets a control's DataContext to the class when you load it in.
Note there's also something called a "view locator": https://stackoverflow.com/questions/5462040/what-is-a-viewmodellocator-and-what-are-its-pros-cons-compared-to-datatemplates
Might be benefitial in your case.
Stack Overflow
What is a ViewModelLocator and what are its pros/cons compared to D...
Can someone give me a quick summary of what a ViewModelLocator is, how it works, and what the pros/cons are for using it compared to DataTemplates?
I have tried finding info on Google but there se...
Thank you, all this information is very helpful. I will attempt both and see which one works. Appreciate it