如何从xml加载值并在所有页面中使用它们?

时间:2014-05-07 19:12:46

标签: c# xml wpf

所以,我正在开发一个小WPF应用程序,主要用于学习。 我的WPF应用程序中有多个页面,每页都有滑块,复选框等。现在,我想要做的是将控制元素中的所有值保存在一个xml文件中。当我重新启动应用程序时,它应该读取该xml并使用存储在其中的值。

我知道如何在一个简单的windowsforms中完成它,但我不能使用WPF ..

1 个答案:

答案 0 :(得分:1)

欢迎使用StackOverflow:D

以下是使用DataContext的简单示例:

我将制作一个显示一些设置的小窗口。

using System.IO;
using System.Windows;
using System.Xml.Serialization;

namespace WpfApplication1
{
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // Create XML sample data
            var settings = new MySettings {Setting1 = "hello !", Setting2 = "hi !"};
            var serializer1 = new XmlSerializer(typeof (MySettings));
            string xml;
            using (TextWriter textWriter = new StringWriter())
            {
                serializer1.Serialize(textWriter, settings);
                xml = textWriter.ToString();
            }

            // Deserialize that sample data to an object
            var serializer2 = new XmlSerializer(typeof (MySettings));
            MySettings deserialize;
            using (var stringReader = new StringReader(xml))
            {
                deserialize = serializer2.Deserialize(stringReader) as MySettings;
            }

            // Use deserialized data as our context
            if (deserialize != null)
            {
                DataContext = deserialize;
            }
        }
    }

    public class MySettings
    {
        public string Setting1 { get; set; }
        public string Setting2 { get; set; }
    }
}

XAML部分(对您来说最感兴趣的是IMO):

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfApplication1="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel d:DataContext="{d:DesignInstance wpfApplication1:MySettings}">
            <TextBlock>Setting 1</TextBlock>
            <TextBlock Text="{Binding Setting1}" />
            <TextBlock>Setting 2</TextBlock>
            <TextBlock Text="{Binding Setting2}" />

        </StackPanel>
    </Grid>
</Window>

所以从这个:

<?xml version="1.0" encoding="utf-16"?>
<MySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Setting1>hello !</Setting1>
  <Setting2>hi !</Setting2>
</MySettings>

我们最终达到了这个目的:

enter image description here