The series continues…
An ItemsControl would be nothing without its collection of Items. In this post, we investigate the “Items” of an ItemsControl, looking at each of the following areas:
If I were rating the technical level of each post in this series, I would put this particular post somewhere in the range of moderate to advanced (but still very approachable :)).
The Items Collection (a.k.a, the ItemCollection)
The “Items” property of an ItemsControl provides access to a collection of objects, or data items, that make up the logical content of the control. The type of this property is ItemCollection. (I will use the terms “Items collection” and “ItemCollection” interchangeably.) The “Type” of each item within the Items collection is Object. So literally any CLR object can be added to an ItemCollection.
We will look at the ItemCollection class, itself, in more detail momentarily, but first, there are a couple of things to note about the Items property declaration on ItemsControl.
1) The Items property is a read-only CLR property.
This means that the collection exposed via the Items property must be instantiated by the control itself. In fact, the ItemCollection class does not even provide a public constructor.
2) The Items property is not backed by a dependency property.
This means that you cannot set a binding directly on the Items property. However, you can definitely bind an ItemsControl to a collection of items. We will look at how this works shortly, but before we do, we should look at the simpler, non-databound (or direct) scenario…
ItemCollection Modes: Direct and ItemsSource
Although the Items property is read only, the provided collection is not necessarily read only. In fact, in earlier posts, we’ve already seen that you can directly add items to an ItemsControl:
<ListBox>
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
<sys:String>Item 3</sys:String>
</ListBox>
Because items are added directly to the ListBox, this is an example of using an ItemCollection in “direct mode”. This is by far the simplest mode to use conceptually. In direct mode, the ItemCollection class works exactly like every other .NET collection. You can directly access all of the expected members of an indexed collection: Add(), Insert(), Remove(), RemoveAt(), IndexOf(), Items[index], Count, etc.
The other mode for an ItemCollection is called “ItemsSource mode”. In ItemsSource mode, the items in the ItemCollection correspond to items in a source collection. That source collection is specified via a separate property on the ItemsControl that is appropriately named “ItemsSource”.
The following shows a typical scenario of an ItemsControl using ItemsSource mode:
<ListView ItemsSource="{Binding Path=Characters}">
<ListView.View>
<GridView>
<GridViewColumn Width="100"
DisplayMemberBinding="{Binding Last}"
Header="Last Name" />
<GridViewColumn Width="100"
DisplayMemberBinding="{Binding First}"
Header="First Name" />
<GridViewColumn Width="60"
DisplayMemberBinding="{Binding Gender}"
Header="Gender" />
</GridView>
</ListView.View>
</ListView>
The ItemsSource property is a dependency property of type IEnumerable. This tells us two important things:
1) The source collection can be any enumerable collection.
2) The ItemsSource property can be established using a binding.
As such, it is the ItemsSource property (in conjunction with the ItemsSource mode of an ItemCollection) that enables an ItemsControl to be databound to a collection.
Sidenote: Although you will most often see the ItemsSource property of an ItemsControl set via a binding, there is no reason that the ItemsSource property cannot be directly set to an enumerable collection, as shown here:
<ListBox ItemsSource="{StaticResource Characters}" />
The Modes are Mutually Exclusive
It should be noted that direct mode and ItemsSource mode are mutually exclusive. An ItemCollection is either in direct mode or in ItemsSource mode, but never both.
Once Items have been explicitly added to the Items collection, it is in direct mode. A subsequent attempt to set the ItemsSource property after entering direct mode will result in an exception.
Similarly, once the ItemsSource property has been set, the Items collection is in ItemsSource mode. A subsequent attempt to directly modify the Items collection (using Add(), Insert(), Remove(), etc) will result in an exception.
The only way to change modes at runtime is to either 1) clear the Items collection via the Clear method (if in direct mode) prior to setting the ItemsSource property, or 2) set the ItemsSource property to null (if in ItemsSource mode) prior to calling the direct access methods of ItemCollection.
Observable Collections Support Dynamic Updates
As noted earlier, in direct mode, changes to the Items collection are made through direct access methods of the ItemCollection class. Any such direct changes made at runtime will cause the visuals to be updated immediately.
But what about dynamic collection changes in ItemsSource mode? How could the Items collection possibly know about changes to the source collection?
The answer is that the ItemCollection cannot know about any such changes unless the source collection chooses to announce those changes by providing change notifications. The way a source collection does this is by fully implementing and supporting the INotifyCollectionChanged interface. Any collection that provides these change notifications is said to be observable.
Dynamic changes to an observable collection will be immediately reflected in the Items collection of any ItemsControl that is bound to the collection. Consequently, these changes will be immediately reflected in the user interface.
The INotifyCollectionChanged interface is not super complex, but ensuring proper implementation does place an extra burden on the source collection. If developers had to implement this interface anytime they wanted to bind to a collection, it would be a huge inconvenience. Luckily, the .NET framework provides a very handy generic template class called ObservableCollection<T>. By creating an instance of this class, you automatically get all of the change notifications without having to do any extra work.
Typically, you will see a collection class derive from ObservableCollection<T>, to create a strongly typed collection, as follows:
public class StringCollection : ObservableCollection<string>
{
}
Any instance of this StringCollection class is fully observable and will serve well as the ItemsSource of an ItemsControl. It can be used exactly like an instance of Collection<string>.
So what if the collection is not observable? Can it still serve as an ItemsSource?
Absolutely. As noted earlier, any enumerable collection can serve as the source of an Items collection. The only caveat is that the Items collection will not be updated dynamically if the source collection changes at runtime. Rather, the collection will be enumerated once and its members will be added to the Items collection when the ItemsSource property is first established. Thereafter, if you want the Items collection to be updated, you must explicitly call the Refresh() method of ItemCollection.
CollectionView: “The Great Equalizer”
If you’ve worked with ItemsControl much, you probably know that sorting, grouping, and filtering are supported via the CollectionView class. This class also supports the notion of currency, which means a CollectionView maintains a current item pointer that can be accessed and moved using methods on the CollectionView.
Every enumerable collection in WPF has a default view. The collection may have multiple other views, each with its own sorting, grouping, and filtering parameters. A common way to establish a view of a collection in markup is to leverage the CollectionViewSource class, as shown here:
<CollectionViewSource x:Key="characterView"
Source="{StaticResource Characters} ">
<CollectionViewSource.SortDescriptions>
<componentModel:SortDescription PropertyName="First" />
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.GroupDescriptions>
<dat:PropertyGroupDescription PropertyName="Last" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
This CollectionViewSource can then be specified as the ItemsSource of an ItemsControl, thereby causing its associated view of the collection to serve as the CollectionView for the control.
“But Dad, I don’t WANT a CollectionView!”
“I didn’t ask what you WANT… As long as you’re living under my roof, you’ll use a CollectionView!”
With WPF, sometimes it’s not as much about what you want, as it is about what the framework needs. The CollectionView class is a classic example. When it comes to binding controls to a collection of data items, the framework needs a way to treat all collections in a consistent manner.
Unfortunately, not all enumerable collections were created equal. For example, IList provides direct index-based access to items, whereas IEnumerable requires that you enumerate all items starting from the beginning of the collection until you come to the index you care about. For another example, consider a collection class that supports the INotifyCollectionChanged interface to provide collection change notifications versus a simple Collection<T> class that provides no such notifications.
The framework architects wanted to support binding to as many different types of collections as possible. But imagine how ugly the code for the ItemsControl class would be if it had to account for differences among collection types with conditional code blocks… if it’s an observable collection, do this, or if it’s an IList, do this, or if it’s an IEnumerable, do this, etc.
Enter the CollectionView class…
To deal with this challenge of disparate collections, WPF introduces the CollectionView class to serve as the great equalizer of enumerable collections. It is the CollectionView class that internally looks at a collection’s supported interfaces and determines how best to deal with the collection. It then surfaces a view of the collection through a well-defined set of properties, methods, and events. Essentially, it allows all collections to be treated by the ItemsControl class as equals.
So whether or not you care about currency, grouping, sorting, filtering, change notifications, etc., the Items collection of an ItemsControl is always maintained internally using a CollectionView. In fact, the ItemCollection class is a CollectionView.
Although true, that last statement is a little misleading since really, ItemCollection is just a wrapper class for an internal CollectionView member. The type of the internal CollectionView is determined by the type of the source collection and the mode of the ItemCollection. In Direct mode, it is always of type InnerItemCollectionView (an internal class designed specifically for direct mode views). In ItemsSource mode, it will be of type CollectionView for an IEnumerable source, ListCollectionView for an IList source, or BindingListCollectionView for an IBindingList or IBindingListView source.
So you’re observable… Who cares?
CollectionView does. We’ve already noted that dynamic changes to observable collections are immediately reflected in the Items collection. It is the CollectionView class that actually listens to the events raised by the collection. So if you’ve ever wondered exactly who is monitoring these events, get a life! Sorry… I meant to say, it’s CollectionView. Now you know.
Performance Considerations around Bound Collections
Keeping in mind that CollectionView serves as the great equalizer of collections, we should look at some performance considerations around binding to collections. We’ve already acknowledged that not all collections support the same features. Often, CollectionView must perform extra work to support its common interface for collections.
One of the major features provided by CollectionView is indexing for an enumerable collection. That is, CollectionView provides direct access to members of the collection by an integer-based index. This means it must support properties like this[int index] and Count, as well as methods like Contains() and IndexOf().
If the source collection already supports indexing, you will see much better performance when binding to the collection. This means that the best candidates for a source collection are those that support the IList interface. It should be noted that ObservableCollection<T> implements IList, so it’s a great choice.
If the source collection does not support index-based access (ICollection or IEnumerable, for example), then CollectionView must do a lot more work to surface the view as an indexed collection. In order to support a property like Count, it may be necessary to enumerate the entire collection. And some methods like Contains(), IndexOf(), and GetItemAt() can be super expensive, since the performance of the algorithm to support these operations is directly proportional to the size of the collection.
So the key perf takeaway is that the source collection should support IList whenever possible.
Items and the Element Trees
The items within the Items collection make up the logical children of the ItemsControl. They are said to be members of the logical tree. For a HeaderedItemsControl, the headers associated with each item will also be logical children of the ItemsControl. (Btw, if you’re not sure what a HeaderedItemsControl is, you should revisit “The ICIQ Test“ and spend a little more time exploring the tooltips after receiving your score.)
If the items in the Items collection happen to be visuals, then they will also be members of the visual tree. If they are not visuals, they will instead be represented visually using an inflated template of visuals. Since the template represents data items, it is called a DataTemplate. For more on that, please tune in for the next episode in this series… ‘D’ is for DataTemplate.