0

を追加します。逆シリアル化のXMLファイルと私はの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; 
} 
    } 

そして、私は私のObservableCollectionが

public ObservableCollection<ProductClass> Products; 

私のクラスは

であるこの

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

を使用していた製品を追加するには

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

をシリアル化します210

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

どのように私は私のリストにいくつかの「製品」を追加することができますか?

+1

例外はありますか。ユーザーはこの1つは、全体の直列化復元リスト –

+0

して、[追加]ボタンをクリックした後、製品がリストに行きます。だから、ユーザーがアプリをオフにしたときに、彼が戻ってきたときに、「リストを復元する」をクリックすると、アプリは彼に古いリストを与えます。ユーザーはプロダクトを追加できるようになりましたが、リストが逆シリアル化されていれば、新しい製品は古い非直列化リストを置き換えます。 – Valerio

+0

を置き換える私は、ユーザーが製品を挿入するテキストボックスを持っている製品を挿入すると – Valerio

答えて

0

あなたのクラスでProductsというパブリックObservableCollection<ProductClass>フィールドを持っていますが、あなたのRecoveryList_Click方法では、あなたが非直列化されたリストを取得し、リストビューのItemsSourceとして設定することもProductsという名前の新しいObservableCollectionを使用しています。彼らは同じ名前ですが、彼らは同じオブジェクトではありません。したがって、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; 
    } 
} 
+0

ありがとうございました!私の一日を作った! – Valerio

関連する問題