0

How can I create a Windows Form with properties provided by an XML document?

Here is such an XML document:

<Form>
   <Size>
     <Width>558</Width> 
     <Height>537</Height> 
   </Size>
   <Text>XML saving</Text> 
   <Name>Form1</Name> 
   <Button>
     <Name>button1</Name> 
     <Text>XML button</Text> 
     <Size>
       <Width>130</Width> 
       <Width>45</Width> 
     </Size>
     <Location>
       <X>14</X> 
       <Y>24</Y> 
     </Location>
   </Button>
 </Form>

Upon loading the form, I need to show the form and the button on it with the values from the XML document.

Can anyone provide any assistance or tutorials on this subject?

3
  • 3
    Are you writing a Windows application (WinForms, WPF), or a website (WebForms, MVC)? Commented Jan 3, 2013 at 14:57
  • I'm writing WinForms app... Commented Jan 3, 2013 at 14:58
  • @DragoFlirt is there something unclear in my answer to you? Feel free to ask any questions Commented Jan 3, 2013 at 17:30

1 Answer 1

4

There is build-in functionality you can use to save and restore form settings. Use application settings binding.

You can bind such properties as Size, Location, Text, etc of form and it's controls to settings, which will be automatically loaded and applied to controls. Steps:

  • Select some control and go to Properties tab
  • Find (ApplicationSettings) property under Data category
  • Open property binding editor
  • Select property you want to save and load from xml and create new setting for that property

If you really need to use your xml, then you should parse it manually. You can create some (extension) methods like (sample with Linq to Xml):

public static void ApplySettings(this Button button, XDocument xdoc)
{
    var settings = xdoc
                 .Descendatns("Button")
                 .SingleOrDefault(b => (string)b.Element("Name") == button.Name);

    if (settings == null)
       return;

    button.Text = (string)settings.Element("Text");
    var location = settings.Element("Location");
    if (location != null)
    {
        button.X = (int)location.Element("X");
        button.Y = (int)location.Element("Y");
    }

    //etc
}

And call those method for each control:

var xdoc = XDocument.Load(settings_file);
button1.ApplySettings(xdoc);
// etc
Sign up to request clarification or add additional context in comments.

1 Comment

Can you change biding to binding in your answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.