一种非常直截了当的方法是,简单地界定数据收集类别(包含数据类别实例的可观察的收集),标明这些类别为可序列的类别,并使用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>
{
}
一些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>
并且把主妇dow与建筑商的代化法和纽特州点击手的序列化法结合起来:
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);
}
}
}