Saving and Restoring Application State

  • 2 minutes to read

There are several types of state an application is often expected to restore upon restart.

  • The state of visual controls such as the selected grouping and column order of a GridControl, or the position of panels in a DockLayoutManager.
  • Dynamically injected modules. These can be automatically injected on startup. The open tabs in a browser is an example.
  • The state of particular View Models.

The Module Injection Framework refers to the first type of state as the visual state. The second and third types are grouped into the logical state.

Configuring Visual State

VisualStateService is responsible for saving visual state. Any control in the visual tree of a particular view can become a serialization root, meaning that its state and the state of all its children down the visual tree can be saved. Add the VisualStateService behavior to a control to mark it as a serialization root.

<UserControl x:Class="ModularApp.Views.ModuleA" ...>

Configuring Logical State

The ISupportState<T> interface allows a ViewModel to provide a state to the MIF, that is applied when the view model is injected as part of a module.

public interface ISupportState<T> {
    void RestoreState(T state);
    T SaveState();

The T-type must provide a default constructor, and if a user type also has the SerializableAttribute applied.

public class ModuleViewModel : ISupportState<ModuleViewModel.Info> {
    public string Caption { get; set; }

    public class Info {
        public string Caption { get; set; }
    Info ISupportState<Info>.SaveState() {
        return new Info() { 
            Caption = this.Caption
    void ISupportState<Info>.RestoreState(Info state) {
        this.Caption = state.Caption;

Saving and Restoring

The application state does not save and restores automatically even after the VisualStateService behavior is attached to suitable controls in XAML, and suitable view models have implemented the ISupportState<T> interface.

The IModuleManagerBase.Save method allows querying the current application state.

void Save(string regionName, out string logicalState, out string visualState);

Both the logical and visual state of a particular region are returned. The application developer is responsible for saving the queried state to persistent storage, for example, application settings.

When an application starts, it may decide whether to restore the saved state or disregard it. The IModuleManagerBase.Restore method restores the application state.

bool Restore(string logicalState, string visualState);

The method returns false if for some reason the state has been corrupted.