【问题标题】:DataGrid Loading/Saving XMLDataGrid 加载/保存 XML
【发布时间】:2012-02-10 09:55:12
【问题描述】:

我有一个相当直接的问题。

如何在 WPF 中获取 DataGrid 以保存/加载原始 XML 文件并能够使用其他控件显示/编辑它们?该应用程序只能离线工作,所以我不需要 SQL。只需打开、编辑数据并将其保存为 XML。

我之前的 WinForms 项目涉及创建一个 DataSet(xsd 文件)和一个 DataTable,并将其绑定到一个 DataGridView。然后通过调用“AddDataTableRow()”添加新项目。通过“ReadXML”、“WriteXML”保存/读取 XML 文件。

我对 WPF 有点陌生,因此非常感谢任何帮助。

【问题讨论】:

标签: wpf xml vb.net visual-studio datagrid


【解决方案1】:

一个非常简单的方法是简单地定义一个数据集合类(一个包含实现 INotifyPropertyChanged 的​​数据类实例的 ObservableCollection),将这些类标记为可序列化并使用 XmlSerializer 进行序列化/反序列化。

一个示例数据类:

[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));
        }
    }
}

和数据收集类:

[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>

以及带有构造函数中的反序列化代码和按钮单击处理程序中的序列化代码的 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);
        }
    }
}

【讨论】:

  • 感谢您的回答,但它会产生一些错误。 ('local' 是一个未声明的前缀。第 6 行,位置 10。' XML 无效。)和(名称 'persons' 在当前上下文中不存在)。将代码转换为 VB 后,这些错误仍然存​​在。
  • 很抱歉给您带来不便,我忽略了这一点。 “local”只是 PersonCollection 类所在的命名空间的 XAML 命名空间声明,在我的示例中为“DataGridTest”。 "persons" 是 MainWindow 类的成员变量。我已经编辑了 XAML 代码示例。将“DataGridTest”替换为项目的命名空间。
  • 我所有的原始代码都是 VB,我使用这个转换器 [developerfusion.com/tools/convert/csharp-to-vb].我发现了大部分错误,但我似乎无法让应用程序运行。我已经在此处上传了所有测试源代码 [mediafire.com/?1wmzeiptct2ujfd].我现在正在学习 C#,但问题是数千行代码已经在 VB 中,从一种语言迁移到另一种语言会很麻烦。
  • 获取完整的示例 C# 项目here.
  • 代码运行良好。几乎解决了所有问题。最后一个问题。例如,如何通过 TextBox 编辑 DataGridItem。我想出了如何使用 DirectCast 获取所选项目。但似乎无法进行编辑。
猜你喜欢
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 2021-03-28
相关资源
最近更新 更多