我们之前通过遍历可视化树并将每个项目保存到 XML 文件来解决这个问题。XML 布局将反映可视化树。重新加载树后,您可以遍历 XML 文件以加载默认值。
private void ForEachControlRecursive(object root, Action<Control> action, bool IsRead)
{
Control control = root as Control;
//if (control != null)
// action(control);
// Process control
ProcessControl(control, IsRead);
// Check child controls
if (root is DependencyObject && CanWeCheckChildControls(control))
foreach (object child in LogicalTreeHelper.GetChildren((DependencyObject)root))
ForEachControlRecursive(child, action, IsRead);
}
ProcessControl
基本上每个控件类型都有一个开关,路由到给定控件的自定义功能。
例如:
private void ProcessControl(TextBox textbox, bool IsRead)
{
//1. textbox.Name; - Control name
//2. Text - Control property
//3. textbox.Text - Control value
if (IsRead)
{
// Class that reads the XML file saving the state of the visual elements
textbox.Text = LogicStatePreserver.GetValue(textbox).ToString();
}
else
{
LogicStatePreserver.UpdateControlValue(textbox, textbox.Text);
}
}