How to save WPF UI state?

.net, c#, settings, tabcontrol, wpf

Solution

To save the state you can bind the relevant control(`Width`, `Height`, `IsSelected` etc.) properties to your binding source's properties(i.e. ViewModel in case of MVVM), this will automatically save your temprory state; for permanent saving you can serialize your ViewModel and save it on disk and obviously load it when required.

like for saving your tree view state you can have `IsExpanded` and `IsSelected` properties in the object(ViewModel) that your `TreeView` is bound to like this -

<Style TargetType="{x:Type TreeViewItem}">
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>

You can also use project settings for saving state of your application, look at this SO Question -

c# - approach for saving user settings in a WPF application?

and this article - User Settings Applied

Problem

I have a `TabControl` and under it I have several elements like `TreeView` and `DataGrid`. When I expand the tree and resize data grid columns, if I then tab to another tab and come back, the entire UI state is forgotten. I have to re-expand the tree and resize the columns. Is there a sensible and existing way to save the UI state? Let's divide this into - - temporary (in memory) and - permanent (on the disk).

Original source

Related problems