Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save WPF UI state?

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 -

  1. temporary (in memory) and
  2. permanent (on the disk).
like image 874
Tower Avatar asked Jun 23 '12 11:06

Tower


1 Answers

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

like image 115
akjoshi Avatar answered Oct 19 '22 03:10

akjoshi