我已经使用带有此方法的按钮来反序列化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;到我的名单?
答案 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;
}
}