Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObservableCollection as DependencyProperty

I'm creating an app in which a list of objects should be intercepted and translated before being displayed on a group of controls. To this end, I've created a DependencyProperty of type ObservableCollection (BackupEntry being a custom class defining information about a database). What I want to happen is that the control will be bound to an ObservableCollection in a MVVM. This collection could be used to initially load the control. Then, when an entry is added via the control interface, it should be added to the internal ObservableCollection which is defined as a DependencyProperty and show up in the collection in the MVVM since they are bound. Here's the code that I'm using:

protected ObservableCollection<BackupEntry> _BackupItems = new ObservableCollection<BackupEntry>();

public static readonly DependencyProperty BackupItemsProperty = DependencyProperty.Register("BackupItems", typeof(ObservableCollection<BackupEntry>), typeof(ExplorerWindow));

public ObservableCollection<BackupEntry> BackupItems
{
    get { return (ObservableCollection<BackupEntry>)GetValue(BackupItemsProperty); }
    set { SetValue(BackupItemsProperty, value); }
}

public ExplorerWindow()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ExplorerWindow), new FrameworkPropertyMetadata(typeof(ExplorerWindow)));
    SetValue(BackupItemsProperty, _BackupItems);
    _BackupItems.CollectionChanged += new NotifyCollectionChangedEventHandler(BackupItems_CollectionChanged);
}

void BackupItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    throw new NotImplementedException();
}

And in the test app:

<my:ExplorerWindow Name="ew" HorizontalAlignment="Left" VerticalAlignment="Top" Width="503" Height="223" BackupItems="{Binding BackupListItems}" />

I created a button on the screen in my test app. When it is clicked, an item is added to BackupListItems. BackupItems_CollectionChanged is never called and the new item is not shown in my collection in my control. Am I totally off track here? What do I need to do to get this working?

like image 991
Dirk Dastardly Avatar asked Aug 12 '11 13:08

Dirk Dastardly


Video Answer


1 Answers

You should follow the pattern given in this question. You need to subscribe to the CollectionChanged event within the PropertyChanged handler as is shown in the above link.

like image 171
Jakub Avatar answered Oct 06 '22 17:10

Jakub