2011-08-16 9 views
1

私はObservableCollectionをカスタムリストボックスで表示しています。 i注意ObservableCollectionがリストビューを更新しない

<ListBox x:Name="listBox1" > 
    <ListBox.ItemTemplate > 
     <DataTemplate > 
      <StackPanel Width="400" Margin="20" > 
       <Button x:Name="pic" Tag="{Binding Id}"> 
        <Button.Template> 
         <ControlTemplate> 
          <TextBlock Text="{Binding title}" TextWrapping="Wrap" FontFamily="Arial" FontSize="28" Tag="{Binding Id}"/> 
         </ControlTemplate> 
        </Button.Template> 
       </Button> 
       <TextBlock Text="{Binding pudate}" TextWrapping="Wrap" FontSize="24"/> 
       <Image Source="{Binding source_icon}" Width="100" Height="60"/> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

XAML

public class lbl 
{ 
    public ObservableCollection<feed> ModifiedItems 
     = new ObservableCollection<feed>(); 

    public lbl() 
    { 
     InitializeComponent(); 
     listBox1.ItemsSource = ModifiedItems ; 
    } 

    public void update(object sender, EventArgs e) 
    { 
     var x = ModifiedItems.Last(); 
     listBox1.Items.Add(x); 
    } 
} 

public class feed 
{ 
    public int ID { get; set; } 
    public int source_id { get; set; } 
    public string title { get; set; } 
    public string source_icon { get; set; } 
    public string url { get; set; } 
    public string pudate { get; set; } 
} 

の下に入手可能である新しいフィードを挿入するかのObservableCollectionからコードの

部品をフィードを除去するように、適用された変更に応じてビューを更新するリストボックスが必要です。これはコードの一部ではありません。 「読み取り専用コレクションでサポートされていない操作」アイテムを追加しようとすると、エラーが表示されます。

ここに投稿されたソリューションを試しましたが、Implementing CollectionChangedと同じエラーが表示されます。

すべてのヘルプしてください、事前

答えて

0

のおかげであなたはリストボックスのItemsSourceを設定しているので、あなたはそれにModifiedItemsコレクションを結合しています。

これは、ModifiedItemsを変更する必要があることを意味し、ListBoxではアイテムを追加/削除できません。したがって、それに応じて更新されます。

public void update(object sender, EventArgs e) 
{ 
    var x = ModifiedItems.Last(); 
    ModifiedItems.Items.Add(x); 
} 

なぜ最後のアイテムを複製したいのですか?しかし、それはあなたがする必要がある変更です。

5

問題は、あなたの更新方法である:

public void update(object sender, EventArgs e) 
{ 
    var x = ModifiedItems.Last(); 
    listBox1.Items.Add(x); 
} 

はあなたのListBoxItemsSourceObservableCollectionあるModifiedItemsに設定されています。したがって、このコレクションにアイテムを追加または削除すると、ListBoxのUIが自動的に更新されます。たとえば、単純に次の操作を行い、あなたのビューに新しい項目を追加する:

ModifiedItems.Add(new feed()); 

これはObservableCollectionの全体のポイントである、ビューはそれを観察することができます!

アイテムを追加/削除するのではなく、既存のアイテムを更新する場合、feedINotifyPropertyChangedを実装する必要があります。

関連する問題