Posted by: rhwilburn | February 15, 2009

Databinding to Collections

If you use WPF then you will be using databinding extensively. This post looks at databinding with respect to collections.

Databinding basics (Background Info):

To databind in .NET currently you are required to provide notification of when the variables you databind to change. This can be done by implementing the INotifyPropertyChanged interface or by implementing the property as a dependency property. For more information on databinding basics, see here.

Collections are slightly different

In the case of collections it is often not important when a collection object changes but rather when the items within that collection change. With that said you will likely need both approaches implemented because if an entire collection is reassigned the binding to the observable collection will be lost as it has been replaced with a new observable collection. It is also possible that others in your team will re-assign the list at some point, so that is why I like to plan for that situation.

private ObservableCollection<String> _names;
internal ObservableCollection<String> Names
{
    get { return _names; }
    set
    {
        _names = value;
        PropertyChanged(this, new PropertyChangedEventArgs("Names"));
    }
}

 

ObservableCollection<T> notifies bindings an item has changed from its CollectionChanged event. The previous code sample shows the INotifyPropertyChanged interface implementation which is required to see if the ObservableCollection assigned to “Names” has been changed. 

In conclusion all Lists that are going to be used for databinding should be ObservableCollections. All properties that are databinded to should implement the INotifyPropertyChanged interface or be dependency properties.


Leave a response

Your response:

Categories