5

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).
akjoshi
  • 15,374
  • 13
  • 103
  • 121
Tower
  • 98,741
  • 129
  • 357
  • 507

1 Answers1

8

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

Community
  • 1
  • 1
akjoshi
  • 15,374
  • 13
  • 103
  • 121
  • 1
    So, I would put all properties I wish to save into my view model? I think my view model would quickly became bloated. Is there a generic approach to take here -- i.e. I have two tree views so do I prefix the `IsExpanded` properties like `FooTreeViewIsExpanded` and `BarTreeViewIsExpanded`? – Tower Jun 23 '12 at 11:38
  • @rFactor - No, IsExpanded property would go to the Model of your TreeViewItem; look at this article for explanation - [Simplifying the WPF TreeView by Using the ViewModel Pattern](http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode) – akjoshi Jun 23 '12 at 11:42
  • @rFactor - and in case you want to save a lot of states of your controls/window then you can use the ProjectSettings approch; see the links provided in answer. – akjoshi Jun 23 '12 at 11:45
  • How do you serialize though? I've tried with: File.WriteAllText("C:\\Form.txt", jsonSerializer.Serialize(currentForm.ViewModel as CustomFormModel)); The custom type has ~50 properties in it's complete inheritance structure, but that's much less than the native WPF classes. I'm getting OutOfMemoryException on a 32GB machine. – MrFox Feb 12 '23 at 19:58