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

Deserialize XML file to ObservableCollection and add object

我已经使用带有此方法的按钮反序列化 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;

我的class是

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

如何将 "Product" 添加到我的列表中?

您的 class 中有一个名为 Products 的 public ObservableCollection<ProductClass> 字段,但是在您的 RecoveryList_Click 方法中,您使用了一个新的 ObservableCollection 也命名为 Products 以检索反序列化列表并将其设置为 ListView 的 ItemsSource。虽然它们同名,但它们不是同一个对象。所以您不能向 ListView 添加新项目。

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

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