How to get FrameworkElement properties before its unloading
It is need to realize UI settings system - loading/saving some properites of UI elements (which can be modified by user in runtime) from/into persistent storage. For example:
- DevExpress grid control - columns width's, visibility, summary area and so on (this control has set of methods pairs like RestoreLayoutFrom/SaveLayoutTo, but SaveLayoutToStream(Xml) doesnt work in grid.Unloaded handler - when grid is disconnected from PresentationSource)
- grid rows/columns, which widths/heights can be adjusted by user via GridSplitter
- sizeable popup controls
It is easy to set up controls properties from settings storage after controls loading/initializing/etc, but how catch the moment before controls unloading (when they still remains in visual tree) in order to retrieve their settings for saving?
Short description
I intend to create singleton - UISettingsManager, which inside has a Dictionary with pairs of [element Uid, element settings data]. In visual container (Window, UserControl) this manager can be used in a way like this:
public partial class PageHeader : UserControl
{
public PageHeader()
{
InitializeComponent();
UISettingsManager.RestoreSettings(myGridControl);
UISettingsManager.RestoreSettings(myPopup);
}
}
myGridControl & myPopup has unique Uid's (in application scope), so UISettingsManager can retrieve their settings from inner dictionary & apply it to the controls; of course UISettingsManager knows, how to work with some different types of controls.
But when it is the right moment to store settings开发者_如何学编程 of controls, which container is Window or UserControl?
I would use the Window's Closing event.
public class MyWindow : Window
{
public MyWindow()
{
this.Closing += new System.ComponentModel.CancelEventHandler(MyWindow_Closing);
}
void MyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Save what I want to here
}
}
This would be the safest bet, because you will always, at some point, close the window.
However, there may be alternatives, including the Unloaded event for a user control.
精彩评论