Sunday, February 06, 2011

Using ObservableCollection with the Portable Library Tools CTP

One of the main goals of the Portable Library Tools is to be able to implement your ViewModel in the Portable Library such that you can share it between your UI in your Silverlight, Windows Phone, or even WPF project.  Unfortunately, this is a bit of a challenge with the Portable Library Tools CTP, because it does not include ObservableCollection<T> or INotifyCollectionChanged.

The reason for this is simple.  The CTP doesn’t have references for System.Windows, and both ObservableCollection<T> and INotifyCollectionChanged are defined in System.Windows.  That they are defined in this assembly isn’t the best in terms of layering, and we have been discussing what to do about that.  But they are there, and we’re looking to address this issue in a future release of the Portable Library Tools.  But that doesn’t help you now, does it?

In fact, ObservableCollection is one of a few common classes that you may find you would like to be able to address from your portable code.  The other one that I’ve run into is HttpUtility.UrlEncode/UrlDecode, so I’ll handle that here as well.

There are two ways to handle this, in general:

  1. If you have a common class or interface that is available to all callers, you can key off of you can use a service locator pattern or some kind of dependency injection (ISomething impl = Factory.GetInstance<ISomething>();)
  2. If you don’t have a common class or interface, you can create a class that allows you to define the specific operations you’re interested in
In the case of ObservableCollection, we have case (2).

Read more: Shawn Burke's Blog