views:

345

answers:

1

Hello,

I'm working on a small program and I would like to save some control states and properties into a configuration file. However I don't want to use the "traditional" settings file due to several reasons, but rather have it serialized or simply saved into a specific file.

For example get window1's TextBox1.Text and serialize it, so that when I start the app I can re-use the old value. Same would go for some Checkboxes for example.

How can this be done ? This is not a "schoolwork" project, since I'm learning C# from scratch in my spare time. I've looked for several methods, but they are simply too complicated by either using a custom serialization class, specifically for that purpouse, or use settings the standard .settings file in Visual Studio. Also, I'm working in C# and the program uses WPF and not MFC.

+2  A: 

We've tackled this before by walking the visual tree and saving each item to an XML file. The XML layout would reflect the visual tree. Upon reloading the tree, you can walk the XML file to load the default values.

    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 basically has a switch for each control type, routing to a customized function for the given control.

For example:

    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);
        }
    }
Jake
thanks ! gonna try it out first thing in the morning and let you know.
lorddarq
by using this method, I should basically go through this above described process for each control or did you mean I should define a all-purpouse class for it ?
lorddarq
I think I i am going to use a form of XML manipulation after all. the above described method is a bit complicated, the settings method only works if you use the XML DOM to manipulate the .config file that's located in the app folder and the ini method is just old.
lorddarq
I have the process run on the main window, and it gets called recursively on the children of the window.
Jake