How to save WPF UI state?

情到浓时终转凉″ 提交于 2019-12-22 08:27:15

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/11169103/how-to-save-wpf-ui-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!