-1

I am practicing building applications using MVVM and WPF+C# by making a "finance application". The application contains several views with their own ViewModels. The views are in a hierarchy and are defined as UserControl with their ViewModel specified in XAML.

One main model contains different financial information that would be presented in views in different ways.

What technique should I use to make sure all ViewModels have access to the main model?

I can come up with three ways:

1. Using a static class which all ViewModels can use.

2. Using MEF with Shared Creation Policy to use a Singleton model that the ViewModels get when they are created.

3. Have each ViewModel have a property for the main model and let parent ViewModels propagate it down the chain.

What solution is recommended for MVVM?

  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask – gnat Oct 2 '18 at 15:00
1

For accessing "global" application state, I generally use option 3 (parent references), with a slight modification. In order to avoid tying a view-model to only being usable on one single type of parent, I use an interface called IHasApplicationState that exposes an ApplicationState property of whatever Type you use to hold the state.

With this pattern, anything that needs to know the state of the application can take this interface as a constructor argument. It can use and store that internally, and pass it off to any child view-models that it needs to create also. It's also DI compliant for easy unit testing.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.