简体   繁体   中英

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).

To save the state you can bind the relevant control( Width , Height , IsSelected etc.) properties to your binding source's properties(ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM