将XML文件反序列化为ObservableCollection并添加对象

时间:2016-04-01 20:12:26

标签: c# xml deserialization win-universal-app xml-deserialization

我已经使用带有此方法的按钮来反序列化ObservableCollection,但在我不能再将对象添加到列表中之后。

private async void RecoveryList_Click(object sender, RoutedEventArgs e)
    {
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("List.xml"); 
DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<ProductClass>));

using (Stream stream = await file.OpenStreamForReadAsync())
{
   ObservableCollection<ProductClass> Products = serializer.ReadObject(stream) as ObservableCollection<ProductClass>;
   ListView1.ItemsSource = Products;
}
   }

并序列化

private async void ButtonSave_Click(object sender, RoutedEventArgs e)
    {
DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<ProductClass>)); 
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync("List.xml", CreationCollisionOption.ReplaceExisting); 

using (Stream stream = await file.OpenStreamForWriteAsync()) 
{
   serializer.WriteObject(stream, Products); 
   ListView1.ItemsSource = Products;
}
    }

添加产品我已使用此

private async void ButtonAdd_Click(object sender, RoutedEventArgs e)
  {
        Products.Add(new ProductClass{ Prodotti = TexBoxInputProducts.Text });           
  }

我的ObservableCollection是

public ObservableCollection<ProductClass> Products;

我的班级是

namespace AppSpesaPhone.Models
{
   public class ProductClass
   {
        public string Prodotti { get; set; }
   }       
}

我如何添加一些&#34;产品&#34;到我的名单?

1 个答案:

答案 0 :(得分:0)

您的班级中有一个名为ObservableCollection<ProductClass>的公开Products字段,但在您的RecoveryList_Click方法中,您使用了一个名为ObservableCollection的新Products来检索反序列化列表并将其设置为ListView的ItemsSource。虽然它们是同一个名字,但它们不是同一个对象。因此,您无法将新项目添加到ListView。

要解决此问题,您可以删除Products方法中的新RecoveryList_Click声明,如下所示,并确保在所有方法中,您正在操作同一个对象。

private async void RecoveryList_Click(object sender, RoutedEventArgs e)
{
    StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("List.xml");
    DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection<ProductClass>));

    using (Stream stream = await file.OpenStreamForReadAsync())
    {
        Products = serializer.ReadObject(stream) as ObservableCollection<ProductClass>;
        ListView1.ItemsSource = Products;
    }
}