views:

18

answers:

1

Imagine the following:

class Repository
{
    private ObservableCollection<ModelClass> _allEntries;
    public ObservableCollection<ModelClass> AllEntries
    {
        get { return _allEntries; }
        set { _allEntries = value; }
    }
    public void RefreshDataFromDB()
    {
        _all = new ObservableCollection(GetMyData()); // whatever method there is
    }
}

Now there are a couple of controls that bind to this collection, e.g.:

<ListView ItemsSource="{Binding Repository.AllEntries, ElementName=Whatever}"/>

The problem now is that if I call the RefreshDataFromDB the bindings get lost (at least it seems so) as the _all is now pointing to new memory part and the bindings still use the old reference. INotifyPropertyChanged does not help me in this case (e.g. putting it in RefreshDataFromDB does not help a lot).

The question would be - how would you handle a case where you replce a collection and want to update its consumers' bindings?

+1  A: 

Yes; you're not modifying the collection, the UI is bound to the collection, and then you replace it with a new one.

You could do this:

_all.Clear();
_all.AddRange(GetMyData());

Hope that helps!


Alternatively, make AllEntries (or All.. your nomenclature seems to change a few times on the post ;)) a DependencyProperty:

public static DependencyProperty AllEntriesProperty = DependencyProperty.Register("AllEntries", typeof(ObservableCollection), typeof(MyClass));

You'd need to make the get/set property too, see here for an example:

http://msdn.microsoft.com/en-us/library/ms752914.aspx

Kieren Johnstone
You don't necessarily need a `DependencyProperty` - `INotifyPropertyChanged` implementation on the property is enough.
Dan Puzey
Thanks, that helped a lot. I didn't think of just clearing the same instance in the first place :)
Jefim