2009-05-10 15 views
1

I持っているコレクション(ShoutBox.Entities)であるプロパティを持つエンティティを保持している。このDependencyPropertyWPF:データバインドされたコレクションに要素を追加する(依存プロパティ)

public static readonly DependencyProperty ShoutBoxProperty = DependencyProperty.Register("ShoutBox",typeof (ShoutBox),typeof (ShoutBoxViewerControl)); 

public ShoutBox ShoutBox 
{ 
    get { return (ShoutBox) GetValue(ShoutBoxProperty); } 
    set { SetValue(ShoutBoxProperty, value); } 
} 

は、それは次のようにxamlにバインドされていますこうした:

<ItemsControl ItemsSource="{Binding ShoutBox.Entries}"> 
. 
. 
</ItemsControl> 

私はそれを最初にバインドすると、期待どおりに動作しますが、私は、このようなように、(同じ制御である方法で)コレクションに項目を追加する必要がございます。

上記の方法で新しい要素を追加すると、項目がItemsControlに表示されないという問題があります。


私の質問は、私は追加してい新しい要素がItemsControlに表示されていないされていない理由のですか?


[編集]

EntriesShoutBox.Entries)は、エントリの種類は何種類でList<ShoutBoxEntry>

答えて

3

のですか? ObservableCollectionまたはICollectionChangedを実装する必要があります。さもなければ、バインディングは新しい項目が追加されたことを知らない。

+0

一覧

+0

を。リストをObservableCollection に変更してください。 http://msdn.microsoft.com/en-us/library/ms668604.aspx – NotDan

+0

アイテムの追加と削除を選択するには、コレクションはINotifyPropertyChangedではなくICollectionChangedを実装する必要があります。 –

0

エントリのタイプを変更すると問題が解決するはずです... Dispatcher.Invokeへの明示的な呼び出しを避けたい場合は、コレクションを作成したスレッドでCollectionChangedイベントとPropertyChangedイベントを発生させるコレクションを作成しました。

public class AsyncObservableCollection<T> : ObservableCollection<T> 
{ 
    private SynchronizationContext _synchronizationContext = SynchronizationContext.Current; 

    public AsyncObservableCollection() 
    { 
    } 

    public AsyncObservableCollection(IEnumerable<T> list) 
     : base(list) 
    { 
    } 

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) 
    { 
     if (SynchronizationContext.Current == _synchronizationContext) 
     { 
      // Execute the CollectionChanged event on the current thread 
      RaiseCollectionChanged(e); 
     } 
     else 
     { 
      // Post the CollectionChanged event on the creator thread 
      _synchronizationContext.Post(RaiseCollectionChanged, e); 
     } 
    } 

    private void RaiseCollectionChanged(object param) 
    { 
     // We are in the creator thread, call the base implementation directly 
     base.OnCollectionChanged((NotifyCollectionChangedEventArgs)param); 
    } 

    protected override void OnPropertyChanged(PropertyChangedEventArgs e) 
    { 
     if (SynchronizationContext.Current == _synchronizationContext) 
     { 
      // Execute the PropertyChanged event on the current thread 
      RaisePropertyChanged(e); 
     } 
     else 
     { 
      // Post the PropertyChanged event on the creator thread 
      _synchronizationContext.Post(RaisePropertyChanged, e); 
     } 
    } 

    private void RaisePropertyChanged(object param) 
    { 
     // We are in the creator thread, call the base implementation directly 
     base.OnPropertyChanged((PropertyChangedEventArgs)param); 
    } 
} 

詳細はここで見つけることができます:問題です http://www.thomaslevesque.com/2009/04/17/wpf-binding-to-an-asynchronous-collection/

関連する問題