【问题标题】:Serialize/Save control property(ex:TextBox.Text) to a custom config file将控件属性(例如:TextBox.Text)序列化/保存到自定义配置文件
【发布时间】:2011-01-19 00:35:15
【问题描述】:

我正在开发一个小程序,我想将一些控件状态和属性保存到配置文件中。但是由于多种原因,我不想使用“传统”设置文件,而是将其序列化或简单地保存到特定文件中。

例如获取 window1 的 TextBox1.Text 并将其序列化,这样当我启动应用程序时,我可以重新使用旧值。例如,某些复选框也是如此。

如何做到这一点?这不是一个“功课”项目,因为我在业余时间从头开始学习 C#。我已经寻找了几种方法,但是它们太复杂了,要么使用专门针对该目的的自定义序列化类,要么使用 Visual Studio 中的标准 .settings 文件设置。另外,我正在使用 C#,程序使用 WPF 而不是 MFC。

【问题讨论】:

    标签: c# controls serializable serialization


    【解决方案1】:

    我们之前通过遍历可视化树并将每个项目保存到 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);
            }
        }
    

    【讨论】:

    • 谢谢!早上第一件事就试一试,然后告诉你。
    • 通过使用这种方法,我基本上应该为每个控件完成上述过程还是你的意思是我应该为它定义一个通用类?
    • 我想我毕竟要使用一种 XML 操作形式。上面描述的方法有点复杂,settings 方法只有在你使用 XML DOM 来操作位于 app 文件夹中的 .config 文件时才有效,并且 ini 方法只是旧的。
    • 我让进程在主窗口上运行,并在窗口的子窗口上递归调用。
    猜你喜欢
    • 2010-11-22
    • 2011-08-08
    • 2016-06-11
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2011-08-24
    相关资源
    最近更新 更多