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?
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:
(ApplicationSettings)
property under Data category 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.