Where to store application settings/state in a MVVM application

前端 未结 3 431
囚心锁ツ
囚心锁ツ 2021-01-30 11:18

I\'m experimenting with MVVM for the first time and really like the separation of responsibilities. Of course any design pattern only solves many problems - not all. So I\'m try

3条回答
  •  伪装坚强ぢ
    2021-01-30 11:59

    Yes, you are on the right track. When you have two controls in your system that need to communicate data, you want to do it in a way that is as decoupled as possible. There are several ways to do this.

    In Prism 2, they have an area that is kind of like a "data bus". One control might produce data with a key that is added to the bus, and any control that wants that data can register a callback when that data changes.

    Personally, I have implemented something I call "ApplicationState". It has the same purpose. It implements INotifyPropertyChanged, and anyone in the system can write to the specific properties or subscribe for change events. It is less generic than the Prism solution, but it works. This is pretty much what you created.

    But now, you have the problem of how to pass around the application state. The old school way to do this is to make it a Singleton. I am not a big fan of this. Instead, I have an interface defined as:

    public interface IApplicationStateConsumer
    {
        public void ConsumeApplicationState(ApplicationState appState);
    }
    

    Any visual component in the tree may implement this interface, and simply pass the Application state to the ViewModel.

    Then, in the root window, when the Loaded event is fired, I traverse the visual tree and look for controls that want the app state (IApplicationStateConsumer). I hand them the appState, and my system is initialized. It is a poor-man's dependency injection.

    On the other hand, Prism solves all of these problems. I kind of wish I could go back and re-architect using Prism... but it is a bit too late for me to be cost-effective.

提交回复
热议问题