简体   繁体   English

DataGrid加载/保存XML

[英]DataGrid Loading/Saving XML

I have a rather straightforward question. 我有一个很简单的问题。

How to I get a DataGrid in WPF to save/load raw XML files and have the ability to display/edit them with other controls? 如何在WPF中获取DataGrid以保存/加载原始XML文件,并能够使用其他控件显示/编辑它们? The application will only work offline so I won't need SQL. 该应用程序只能脱机工作,因此我不需要SQL。 Just simply open, edit and save data to XML. 只需简单地打开,编辑并将数据保存到XML。

My previous projects with WinForms involved creating a DataSet (xsd file) and a DataTable, bound it to a DataGridView. 我以前使用WinForms进行的项目涉及创建一个DataSet(xsd文件)和一个DataTable,并将其绑定到DataGridView。 Then add new items with by calling "AddDataTableRow()". 然后通过调用“ AddDataTableRow()”添加新项。 Save/Read XML files by "ReadXML", "WriteXML". 通过“ ReadXML”,“ WriteXML”保存/读取XML文件。

I'm kinda new to WPF so any help would be very appreciated. 我是WPF的新手,所以我们将不胜感激。

A very straightforward approach would be to simply define a data collection class (an ObservableCollection containing instances of a data class which implements INotifyPropertyChanged), mark these classes as serializable and use XmlSerializer for serializing/deserializing. 一种非常简单的方法是简单地定义数据收集类(一个ObservableCollection,其中包含实现INotifyPropertyChanged的数据类的实例),将这些类标记为可序列化,然后使用XmlSerializer进行序列化/反序列化。

A sample data class: 样本数据类:

[Serializable]
public class Person : INotifyPropertyChanged
{
    private string firstName;
    private string lastName;

    public event PropertyChangedEventHandler PropertyChanged;

    public string FirstName
    {
        get { return firstName; }
        set
        {
            firstName = value;
            NotifyPropertyChanged("FirstName");
        }
    }

    public string LastName
    {
        get { return lastName; }
        set
        {
            lastName = value;
            NotifyPropertyChanged("LastName");
        }
    }

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

and the data collection class: 和数据收集类:

[Serializable]
public class PersonCollection : ObservableCollection<Person>
{
}

Some XAML: 一些XAML:

<Window x:Class="DataGrid.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataGridTest"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:PersonCollection x:Key="PersonCollection"/>
        <CollectionViewSource x:Key="PersonCollectionViewSource" Source="{StaticResource PersonCollection}"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <DataGrid Name="dataGrid" Margin="2" ItemsSource="{Binding Source={StaticResource PersonCollectionViewSource}}"/>
        <StackPanel Grid.Row="1" Margin="2" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Content="Save" Click="Button_Click"/>
        </StackPanel>
    </Grid>
</Window>

And class MainWindow with the deseralization code in the constructor and the serialization code in the button click handler: 并在类MainWindow中使用构造函数中的反序列化代码和按钮单击处理程序中的序列化代码:

public partial class MainWindow : Window
{
    private PersonCollection persons;

    public MainWindow()
    {
        InitializeComponent();

        persons = (PersonCollection)Resources["PersonCollection"];

        XmlSerializer serializer = new XmlSerializer(typeof(PersonCollection));

        using (FileStream stream = new FileStream("Persons.xml", FileMode.Open))
        {
            IEnumerable<Person> personData = (IEnumerable<Person>)serializer.Deserialize(stream);

            foreach (Person p in personData)
            {
                persons.Add(p);
            }
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(PersonCollection));

        using (FileStream stream = new FileStream("Persons.xml", FileMode.Create))
        {
            serializer.Serialize(stream, persons);
        }
    }
}

Use Linq and XElement instead of an Xdocument and data sets. 使用Linq和XElement代替Xdocument和数据集。

http://msdn.microsoft.com/en-us/library/bb669141.aspx http://msdn.microsoft.com/en-us/library/bb669141.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM