Skip to main content

ReadOnlyCollection<T> meets BindingList<T>...

Okay my first post and I was going to jump right in and try a fill a gap in the blogging worlds knowledge about having a read only collection that supports notifications of modifications to collection members when programming in .Net - what happens when ReadOnlyCollection<T> meets BindingList<T>

The simple answer to that question is ReadOnlyObservableCollection<T> in version 3.0 or higher - it provides the exactly functionality I require and gets away from the awful 'Binding' prefix name which has to much association with 'Data Binding' in the MS world. But in version 2.0 you don't have a such a luxury :).

This is really the sub-text of this post and the problem I'm trying to solve - How can I observe events on a domain entities (including collections) when implementing Domain Driven Design in a winforms environment that utilises an MVC(P) pattern?

If you don't know much about Domain Drive Design check the out website and for a great set of posts on see Casey Charlton's blog and accompanying DDD website.

Back to the question, By implementing the interfaces INotifyCollectionChanged and INotifyPropertyChanged we allow the domain entities and value objects to notify anyone who is interested when their state changes. So if we have our entities deriving off a base class that implements INotifyPropertyChanged and a property changs we fire the event PropertyChanged and anyone observing gets notified.

A simple base class that implments INotifyPropertyChanged:

    public abstract class Observable : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        protected void NotifyPropertyChangedObservers(string propertyName)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

And a domain entity that derives from this, finding a quick and easy domain to model is tricky :)

    public sealed class Person : Observable
    {
        private string firstName;
        private string lastName;

        public Person(string firstName, string lastName)
        {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public string FirstName
        {
            get { return firstName; }
            set { SetProperty(ref firstName, value, "FirstName"); }
        }

        public string LastName
        {
            get { return lastName; }
            set { SetProperty(ref lastName, value, "LastName"); }
        }

        private void SetProperty(ref T existingValue, T newValue, string propertyName)
        {
            if (!Object.Equals(newValue, existingValue))
            {
                existingValue = newValue;
                NotifyPropertyChangedObservers(propertyName);
            }
        }
    }

So this mechanism work great, I'm now able to observe any changes to any value type properties on the domain entities - this is really useful in a our Model View Controller Presenter pattern, we can now bind our Model to the View and the View now gets automatically notified of changes to the Model and knows how to handle updating the UI. It should be said we don't couple the Model directly to the View we use a Presenter hence the MVC(P), the Presenter creates a Presentation wrapper around the Model that is bound to the View.

But what about when the properties start to represent more complicated such as collections?

Lets tackle the .Net 3.0 version first- Simple we use the ReadOnlyObservableCollection<T> and we now have the advantage of observing any changes to the entities inside the collection but we don't let anyone change the contents of the collection - you wouldn't want anyone to come along and just add more children to your family without your say so would you :)

    public sealed class Family : Observable
    {
        private Person firstParent;
        private Person secondParent;

        private ObservableCollection children;

        public Family(Person firstParent, Person secondParent, IList children)
        {
            this.firstParent = firstParent;
            this.secondParent = secondParent;

            this.children = new ObservableCollection();
            foreach (Person child in children)
                this.children.Add(child);
        }

        public Person FirstParent
        {
            get { return firstParent; }            
        }

        public Person SecondParent
        {
            get { return secondParent; }            
        }

        public ReadOnlyObservableCollection Children
        {
            get { return new ReadOnlyObservableCollection(children); }
        }

        private void SetProperty(ref T existingValue, T newValue, string propertyName)
        {
            if (!Object.Equals(newValue, existingValue))
            {
                existingValue = newValue;
                NotifyPropertyChangedObservers(propertyName);
            }
        }
    }

Now to do this in .Net 2.0 becomes a bit of an issue we don't have the luxury of ObservableCollection or ReadonlyObservableCollection we have to role our own implementation that some how combines the functionality of ReadOnlyCollection and BindingList. My first attempt was to derive from BindingList and override any method that modifies the list

    public sealed class ReadOnlyBindingList : BindingList
    {
      ...
    }

But I discovered an important thing I wasn't able to override methods like 'Add', 'Remove' I had to use the 'new' operator which set alarm bells off - this is a code smell if ever I've seen one. This was confirmed when talking to another dev who pointed out this would break Liskov's Subsitution Princple if I were to replace an use of my ReadOnlyBindingList with a normal BindingList. So that attempt fails before getting of the launch pad...

So the answer is to use containment of the BindingList collection and implement the IBindingList interface...

    public sealed class ReadOnlyObservableCollection<T> : IBindingList<T> where T : class
    {
        public event ListChangedEventHandler ListChanged = delegate { };

        private BindingList<T> innerList;

        public ReadOnlyObservableCollection(IList list)
        {
            innerList = new BindingList<T>();
            foreach (T item in list)
                innerList.Add(item);

            innerList.ListChanged += HandleListChanged;
        }

        void IBindingList.AddIndex(PropertyDescriptor property)
        {  
            ((IBindingList)innerList).AddIndex(property);
        }

        public object AddNew()
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool AllowEdit
        {
            get { return true; }
        }

        public bool AllowNew
        {
            get { return false; }
        }

        public bool AllowRemove
        {
            get { return false; }
        }

        void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
        {
            ((IBindingList)innerList).ApplySort(property, direction);
        }

        int IBindingList.Find(PropertyDescriptor property, object key)
        {
            return ((IBindingList)innerList).Find(property, key);
        }

        bool IBindingList.IsSorted
        {
            get { return ((IBindingList)innerList).IsSorted; }
        }

        void IBindingList.RemoveIndex(PropertyDescriptor property)
        {
            ((IBindingList)innerList).RemoveIndex(property);
        }

        public void RemoveSort()
        {
            ((IBindingList)innerList).RemoveSort();
        }

        ListSortDirection IBindingList.SortDirection
        {
            get { return ((IBindingList)innerList).SortDirection; }
        }

        PropertyDescriptor IBindingList.SortProperty
        {
            get { return ((IBindingList)innerList).SortProperty; }
        }

        bool IBindingList.SupportsChangeNotification
        {
            get { return ((IBindingList)innerList).SupportsChangeNotification; }
        }

        bool IBindingList.SupportsSearching
        {
            get { return ((IBindingList)innerList).SupportsSearching; }
        }

        bool IBindingList.SupportsSorting
        {
            get { return ((IBindingList)innerList).SupportsSorting; }
        }

        public int Add(object value)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool Contains(object value)
        {
            return innerList.Contains(value as T);
        }

        public int IndexOf(object value)
        {
            return innerList.IndexOf(value as T); 
        }

        public void Insert(int index, object value)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool IsFixedSize
        {
            get { return true; }
        }

        public void Remove(object value)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public void RemoveAt(int index)
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public object this[int index]
        {
            get { return innerList[index]; }
            set { throw new NotImplementedException("ReadOnlyObservableCollection!"); }
        }

        public T this[int index]
        {
            get { return (T)innerList[index]; }
            set { throw new NotImplementedException("ReadOnlyObservableCollection!"); }
        }

        public void CopyTo(Array array, int index)
        {
            innerList.CopyTo((T[])array, index);
        }

        bool ICollection.IsSynchronized
        {
            get { return ((ICollection)innerList).IsSynchronized; }
        }

        object ICollection.SyncRoot
        {
            get { return ((ICollection)innerList).SyncRoot; }
        }

        public bool RaisesItemChangedEvents
        {
            get { return true; }
        }

        public void Clear()
        {
            throw new NotImplementedException("ReadOnlyObservableCollection!");
        }

        public bool IsReadOnly
        {
            get { return true; }
        }

        public int Count
        {
            get { return innerList.Count; }
        }

        public System.Collections.IEnumerator GetEnumerator()
        {
            return innerList.GetEnumerator();
        }

        private void HandleListChanged(object sender, ListChangedEventArgs args)
        {
            NotifyListChangedObservers(args);
        }

        private void NotifyListChangedObservers(ListChangedEventArgs args)
        {
            ListChanged(this, args);
        }
    }

So to implement a ReadOnlyObserableCollection collection in .Net 2.0 can be done relatively easily, but it's a no brainer if you're using a newer version of the framework :)

There is one issue relating to providing observable entities in the domain, am I coupling the presentation functionality into the domain entities by doing this?

I don't think this is as black and white as using repositories from domain entities - I don't believe you should use repositories in domain entities. The reason I believe this is because by providing observable entities in the domain doesn't mean they will be used by the presentation nor am I doing this to support any presentation pattern.

Comments

Post a Comment

Popular posts from this blog

WPF tips & tricks: Dispatcher thread performance

Not blogged for an age, and I received an email last week which provoked me back to life. It was a job spec for a WPF contract where they want help sorting out the performance of their app especially around grids and tabular data. I thought I'd shared some tips & tricks I've picked up along the way, these aren't probably going to solve any issues you might be having directly, but they might point you in the right direction when trying to find and resolve performance issues with a WPF app. First off, performance is something you shouldn't try and improve without evidence, and this means having evidence proving you've improved the performance - before & after metrics for example. Without this you're basically pissing into the wind, which can be fun from a developer point of view but bad for a project :) So, what do I mean by ' Dispatcher thread performance '? The 'dispatcher thread' or the 'UI thread' is probably the most

Showing a message box from a ViewModel in MVVM

I was doing a code review with a client last week for a WPF app using MVVM and they asked ' How can I show a message from the ViewModel? '. What follows is how I would (and have) solved the problem in the past. When I hear the words ' show a message... ' I instantly think you mean show a transient modal message box that requires the user input before continuing ' with something else ' - once the user has interacted with the message box it will disappear. The following solution only applies to this scenario. The first solution is the easiest but is very wrong from a separation perspective. It violates the ideas behind the Model-View-Controller pattern because it places View concerns inside the ViewModel - the ViewModel now knows about the type of the View and specifically it knows how to show a message box window: The second approach addresses this concern by introducing the idea of messaging\events between the ViewModel and the View. In the example below

Implementing a busy indicator using a visual overlay in MVVM

This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whilst it's retrieving or rendering data. Now we could have done this by launching a child dialog window but that feels rather out of date and clumsy, we wanted a more modern pattern similar to the way <div> overlays are done on the web. Imagine we have the following simple WPF app and when 'Click' is pressed a busy waiting overlay is shown for the duration entered into the text box. What I'm interested in here is not the actual UI element of the busy indicator but how I go about getting this to show & hide from when using MVVM. The actual UI elements are the standard Busy Indicator coming from the WPF Toolkit : The XAML behind this window is very simple, the important part is the ViewHost. As you can see the ViewHost uses a ContentPresenter element which is bound to the view model, IMainViewModel, it contains 3 child v