<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dr. WPF &#187; Collections</title>
	<atom:link href="http://drwpf.com/blog/category/collections/feed/" rel="self" type="application/rss+xml" />
	<link>http://drwpf.com/blog</link>
	<description>Drinking (and serving) the WPF Kool-Aid since 2002</description>
	<lastBuildDate>Sun, 09 May 2010 06:59:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>ItemsControl:  &#039;E&#039; is for Editable Collection</title>
		<link>http://drwpf.com/blog/2008/10/20/itemscontrol-e-is-for-editable-collection/</link>
		<comments>http://drwpf.com/blog/2008/10/20/itemscontrol-e-is-for-editable-collection/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 09:03:53 +0000</pubDate>
		<dc:creator>Dr. WPF</dc:creator>
				<category><![CDATA[Collections]]></category>
		<category><![CDATA[ItemsControl]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://drwpf.com/blog/?p=42</guid>
		<description><![CDATA[
Dear Dr. WPF,
As of late, a serein has come upon me in the world of wpf and databinding, hence I&#8217;m writing to you in my desperate search for some kind of remedy before there will be a hey rube.
Whilst having an ObservableCollection of &#8220;Person&#8221; objects, and creating a collectionview for this and also adding a [...]]]></description>
			<content:encoded><![CDATA[<div class="jbr">
<p><em>Dear Dr. WPF,</em></p>
<p><em>As of late, a serein has come upon me in the world of wpf and databinding, hence I&#8217;m writing to you in my desperate search for some kind of remedy before there will be a hey rube.</em></p>
<p><em>Whilst having an ObservableCollection of &#8220;Person&#8221; objects, and creating a collectionview for this and also adding a SortDescription on a &#8220;Name&#8221; property on the &#8220;Person&#8221; object, I noticed that if I change the &#8220;Name&#8221; property on one of the objects (they are shown in a listbox, having the &#8220;Name&#8221; property databound to a textblock), and thereafter calling Refresh() on the CollectionView, the refresh will actually take more than a second with only about 50 items.</em></p>
<p><em>Ok, if I measure the call to Refresh() it doesn&#8217;t take more than 100 ms or so, but like the call sets in motion alot of other things that will happen after my method has exited, which is understandable since the documentation states that the whole view is recreated and therefore I assume the whole tree of items of the visualtree concerned is re-created too.</em></p>
<p><em>If I instead just remove the item, and just re-insert it, it&#8217;s as close as I can get to instantaneous. perfect! BUT! Since I&#8217;m a quidnunc I won&#8217;t be satisfied with this! So I&#8217;m asking the great Dr, that has given us all such great in depth knowledge in the past, what can we do about this in a more generic fashion? Can we speed up the &#8220;Refresh()&#8221; somehow? What would you suggest I do if I have a collection of a type that I don&#8217;t know about at compile time? How can I remove / add an item then!</em></p>
<p><em>Or am I simply lost in my path to enlightenment ?</em></p>
<p><em>I shall not dissert anymore, but hope to hear from the good Dr, perhaps in a blogpost touching this subject as I feel it to be of greater interest to the public health in the land of wpf.</em></p>
<p><em>Best regards,<br />
Patient-X</em></p>
<div>
<hr /></div>
<p>Dear Patient-X,</p>
<p>I&#8217;ve been wondering what I could file under the letter &#8216;E&#8217; in this series, and now you&#8217;ve afforded me the perfect opportunity! <img src='http://drwpf.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>No, you are not lost in your path to enlightenment. The true path will lead you to a new feature in .NET 3.5 SP1 called an &#8220;editable&#8221; collection view. More on that momentarily&#8230; First, let&#8217;s examine exactly what is happening in your scenario.</p>
<p><strong>Understanding the ListCollectionView Class</strong></p>
<p>You are binding to a list of items. More specifically, you are binding to a collection of Person objects (namely an ObservableCollection&lt;Person&gt;) that, in turn, implements the IList interface. The binding engine will automatically generate a ListCollectionView for such a collection. The ListCollectionView class provides support for sorting, grouping, and filtering your collection when it is the ItemsSource for an ItemsControl. (See <em><a href="http://drwpf.com/blog/?p=18" target="_blank">&#8216;C&#8217; is for Collection</a></em> for more information.)</p>
<p>For the purposes of this discussion, let&#8217;s look at a similar scenario using the following collection of Character objects (borrowed from <em><a href="http://drwpf.com/blog/?p=32" target="_blank">&#8216;I&#8217; is for Item Container</a></em>):</p>
<div>
<pre><span style="font-family: Courier New;">    &lt;<span style="color: #993300;">src:CharacterCollection</span> <span style="color: #ff0000;">x:Key</span>="Characters"&gt;
      &lt;<span style="color: #993300;">src:Character</span> <span style="color: #ff0000;">First</span>="Homer" <span style="color: #ff0000;">Last</span>="Simpson"
          <span style="color: #ff0000;">Gender</span>="Male" <span style="color: #ff0000;">Image</span>="images/homer.png" /&gt;
      &lt;<span style="color: #993300;">src:Character</span> <span style="color: #ff0000;">First</span>="Marge" <span style="color: #ff0000;">Last</span>="Bouvier"
          <span style="color: #ff0000;">Gender</span>="Female" <span style="color: #ff0000;">Image</span>="images/marge.png" /&gt;
      &lt;<span style="color: #993300;">src:Character</span> <span style="color: #ff0000;">First</span>="Bart" <span style="color: #ff0000;">Last</span>="Simpson"
          <span style="color: #ff0000;">Gender</span>="Male" <span style="color: #ff0000;">Image</span>="images/bart.png" /&gt;
      &lt;<span style="color: #993300;">src:Character</span> <span style="color: #ff0000;">First</span>="Lisa" <span style="color: #ff0000;">Last</span>="Bouvier"
          <span style="color: #ff0000;">Gender</span>="Female" <span style="color: #ff0000;">Image</span>="images/lisa.png" /&gt;
      &lt;<span style="color: #993300;">src:Character</span> <span style="color: #ff0000;">First</span>="Maggie" <span style="color: #ff0000;">Last</span>="Simpson"
          <span style="color: #ff0000;">Gender</span>="Female" <span style="color: #ff0000;">Image</span>="images/maggie.png" /&gt;
    &lt;/<span style="color: #993300;">src:CharacterCollection</span>&gt;</span></pre>
</div>
<p>To demonstrate grouping and sorting for our collection, we can define a CollectionViewSource object in markup, as shown below:</p>
<div>
<pre><span style="font-family: Courier New;">    &lt;<span style="color: #993300;">CollectionViewSource </span><span style="color: #ff0000;">x:Key</span>="CharacterCollectionView"
        <span style="color: #ff0000;">Source</span>="{<span style="color: #993300;">Binding</span> <span style="color: #ff0000;">Source</span>={<span style="color: #993300;">StaticResource</span> <span style="color: #ff0000;">Characters</span>}}"&gt;
      &lt;<span style="color: #993300;">CollectionViewSource.GroupDescriptions</span>&gt;
        &lt;<span style="color: #993300;">PropertyGroupDescription</span> <span style="color: #ff0000;">PropertyName</span>="Gender"/&gt;
      &lt;/<span style="color: #993300;">CollectionViewSource.GroupDescriptions</span>&gt;
      &lt;<span style="color: #993300;">CollectionViewSource.SortDescriptions</span>&gt;
        &lt;<span style="color: #993300;">cm:SortDescription</span> <span style="color: #ff0000;">PropertyName</span>="First" /&gt;
      &lt;/<span style="color: #993300;">CollectionViewSource.SortDescriptions</span>&gt;
    &lt;/<span style="color: #993300;">CollectionViewSource</span>&gt;</span></pre>
</div>
<p>When this CollectionViewSource is set as the ItemsSource of a ListBox, it will yield a view of the collection (namely, a ListCollectionView) in which the characters are grouped by gender and sorted by first name. Here is what the ListBox declaration might look like:</p>
<div>
<pre><span style="font-family: Courier New;">  &lt;<span style="color: #993300;">ListBox </span><span style="color: #ff0000;">Name</span>="lb" <span style="color: #ff0000;">HorizontalAlignment</span>="Center" <span style="color: #ff0000;">VerticalAlignment</span>="Center"
      <span style="color: #ff0000;">ItemsPanel</span>="{<span style="color: #993300;">StaticResource</span> <span style="color: #ff0000;">HorizontalItemsPanel</span>}"
      <span style="color: #ff0000;">ItemsSource</span>="{<span style="color: #993300;">Binding</span> <span style="color: #ff0000;">Source</span>={<span style="color: #993300;">StaticResource</span> <span style="color: #ff0000;">CharacterCollectionView</span>}}"
      <span style="color: #ff0000;">ItemContainerStyle</span>="{<span style="color: #993300;">StaticResource</span> <span style="color: #ff0000;">CharacterContainerStyle</span>}"&gt;
    &lt;<span style="color: #993300;">ListBox.GroupStyle</span>&gt;
      &lt;<span style="color: #993300;">GroupStyle</span> <span style="color: #ff0000;">Panel</span>="{<span style="color: #993300;">StaticResource</span> <span style="color: #ff0000;">HorizontalItemsPanel</span>}" /&gt;
    &lt;/<span style="color: #993300;">ListBox.GroupStyle</span>&gt;
  &lt;/<span style="color: #993300;">ListBox</span>&gt;</span></pre>
</div>
<p>The image below depicts our ListBox with grouping and sorting.</p>
<p><img src="http://drwpf.com/blog/Portals/0/Images/ItemsControl/E/GroupedAndSortedCharacters.jpg" alt="" /></p>
<p>You can <a href="http://drwpf.com/blog/Portals/0/Samples/EditableCollectionSample.zip">download the sample</a> for this post to see the complete item template, item container style, and group item style.</p>
<p><strong>Dynamically Updating Items is Problematic</strong></p>
<p>Ideally, applying a sort order to a CollectionView would result in a grouped and sorted view of the collection that is fully maintained even when items within the collection are changed. Unfortunately, a ListCollectionView only groups and sorts its items when the view is first created (or when new items are added to the source collection, assuming that the source collection is observable). A ListCollectionView will <strong>*not*</strong> monitor changes to properties on each existing item within the collection.</p>
<p>For example, if you execute code at runtime to dynamically change Bart&#8217;s name to &#8220;Mandy&#8221;, the ListCollectionView will be unaware of that change and the item will <em>not</em> appear in its proper sorted location after the change. Furthermore, if Bart finally gets the operation he deserves (and secretly desires) and his gender is updated accordingly, the changed item will <em>not</em> move to its proper group. Here is some simple code to perform these changes:</p>
<div>
<pre><span style="font-family: Courier New;">    <span style="color: #008080;">Character </span>bart = lb.Items[0] <span style="color: #0000ff;">as</span> <span style="color: #008080;">Character</span>;
    bart.First = <span style="color: #993300;">"Mandy"</span>;
    bart.Gender = <span style="color: #008080;">Gender</span>.Female;</span></pre>
</div>
<p>The image below depicts the sorting and grouping errors that are present after these changes:</p>
<p><img src="http://drwpf.com/blog/Portals/0/Images/ItemsControl/E/ScrewedUpGroupingAndSorting.jpg" alt="" /></p>
<p>Note, that the item template <em>did</em> indeed update according to the name and gender change (because the Character object raises the appropriate change notifications for these properties), but the ListCollectionView did <em>not</em> update its view of the items. As a result, the changed item is no longer in the correct sort location or group.</p>
<p><strong>Refreshing a CollectionView</strong></p>
<p>If you are using .NET 3.5 or earlier, you can force a CollectionView to be updated at runtime by calling its Refresh() method. Then the items will once again be properly grouped and sorted. Here is a routine that includes the Refresh() call:</p>
<div>
<pre><span style="font-family: Courier New;">    <span style="color: #008080;">Character </span>bart = lb.Items[0] <span style="color: #0000ff;">as</span> <span style="color: #008080;">Character</span>;
    bart.First = <span style="color: #993300;">"Mandy"</span>;
    bart.Gender = <span style="color: #008080;">Gender</span>.Female;
    (lb.ItemsSource <span style="color: #0000ff;">as</span> <span style="color: #008080;">ListCollectionView</span>).Refresh();</span></pre>
</div>
<p>After calling Refresh(), the modified character now appears in the correct group and sort location, as shown here:</p>
<p><img src="http://drwpf.com/blog/Portals/0/Images/ItemsControl/E/ModifiedCharactersAfterRefresh.jpg" alt="" /></p>
<p>Unfortunately, the Refresh() method results in a complete regeneration of the view. It is a rather drastic operation, to say the least. Furthermore, when a Refresh() occurs within the view, it raises a CollectionChanged notification and supplies the Action as &#8220;Reset&#8221;. The ItemContainerGenerator for the ListBox receives this notification and responds by discarding all the existing visuals for the items. It then completely regenerates new item containers and visuals. (See <em><a href="http://drwpf.com/blog/?p=32" target="_blank">&#8216;I&#8217; is for Item Container</a></em> and <a href="http://drwpf.com/blog/?p=37" target="_blank"><em>&#8216;G&#8217; is for Generator</em></a> for more information on item containers and container generation.) Again, this is a drastic (and often very expensive) operation.</p>
<p><strong>Increasing Refresh Performance is Difficult</strong></p>
<p>You raised the question, <em>&#8220;Can we speed up the &#8220;Refresh()&#8221; somehow?&#8221;</em></p>
<p>Unfortunately, the very nature of the refresh operation makes this difficult. For the mundane reasons, keep reading&#8230; otherwise, feel free to skip ahead to <em><a href="#ABetterOption">A Better Option</a></em>.</p>
<p>Theoretically, you could derive your own custom collection view from the ListCollectionView class and override its Refresh() method. Then you could perhaps implement a routine that intelligently regenerates the view in a minimalistic manner by comparing the source collection to the view collection.</p>
<p>Such a routine would need to move existing items to their new locations in the view, add items that were not previously present, and remove items that should no longer be present. All of these changes would need to be made per the view&#8217;s sorting, grouping, and filter criteria. For each change, the view would need to raise a very specific CollectionChanged notification (Add, Remove, or Move) for consumption by the ItemContainerGenerator of the owning ItemsControl.</p>
<p>Not only would such a synchronization routine be complex, but it is also likely to be <em>even more expensive</em> than simply resetting the entire collection. There will be some number, <em>n</em>, where discrete Add, Remove, and Move change notifications for <em>n</em> or fewer changes is indeed more performant than a single Reset notification. Unfortunately, it will be very difficult to heuristically determine the appropriate value for <em>n</em>.</p>
<p><strong><a class="FCK__AnchorC FCK__AnchorC" name="ABetterOption"></a>A Better Option: Remove and Re-Add</strong></p>
<p>A better approach, especially if you are stuck on pre-3.5 SP1 bits, is to do precisely what you describe in your email. Namely, do not call Refresh() at all, but instead, remove the target item from the observable collection, modify its properties, and then re-add it to the collection, as shown here:</p>
<pre><span style="font-family: Courier New;">    <span style="color: #008080;">Character </span>bart = lb.Items[0] <span style="color: #0000ff;">as</span> <span style="color: #008080;">Character</span>;
    <span style="color: #008080;">CharacterCollection </span>characters = FindResource(<span style="color: #993300;">"Characters"</span>) <span style="color: #0000ff;">as</span> <span style="color: #008080;">CharacterCollection</span>;
    characters.Remove(bart);
    bart.First = <span style="color: #993300;">"Mandy"</span>;
    bart.Gender = <span style="color: #008080;">Gender</span>.Female;
    characters.Add(bart);</span></pre>
<p>The ListCollectionView will detect the removal of the old item and raise the appropriate Remove notification so that the ItemContainerGenerator can remove the associated container and visuals. It will also detect the addition of the modified item and insert it at the correct location within its view of the source collection (again, per the grouping, sorting, and filter criteria). Then it will raise the necessary Add notification so that a new item container and item visuals can be generated.</p>
<p>This solution is obviously not perfect! One problem that may not be immediately evident is that adding and removing an item from the source collection effects the ListCollectionView&#8217;s notion of currency (&#8221;current item&#8221;). For example, if the Bart character was the current item before it was removed from the collection, that state will be lost. If this is important to your scenario, you must add additional code around the remove/re-add routine to save and restore currency.</p>
<p><strong>An Even Better Option: IEditableObject</strong></p>
<p>As mentioned earlier, <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ab99342f-5d1a-413d-8319-81da479ab0d7&amp;DisplayLang=en" target="_blank">.NET 3.5 SP1</a> enables an even better approach that solves many of the problems present in the Refresh() and Remove/Re-Add solutions. Namely, it allows you to implement an <em>IEditableObject</em> interface on your datamodel objects (or on your viewmodel objects, if you are using the <a href="http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx" target="_blank">model-view-viewmodel pattern</a>). This new interface allows for transactional changes (edit, cancel, and commit) on the object.</p>
<p>The framework supports the transactional model by implementing another new interface called <em>IEditableCollectionView</em> on the existing list-based CollectionView classes (ListCollectionView and BindingListCollectionView). This interface works in conjunction with collection items that implement the IEditableObject interface.</p>
<p>In this new approach, when you need to change an item, you can first call the EditItem() method of the collection view, then make the required changes to the item, and finally, call the CommitEdit() method of the collection view. If you decide that you don&#8217;t want to commit the changes, you can call the CancelEdit() method of the collection view.</p>
<p>It is worth noting that the ItemCollection class also implements the IEditableCollectionView interface. Since the Items property of an ItemsControl is of type ItemCollection (see <a href="http://drwpf.com/blog/?p=18" target="_blank"><em>&#8216;C&#8217; is for Collection</em></a>), it provides handy access to the methods of IEditableCollectionView. As long as you know the source collection is an IList, you can safely call the IEditableCollectionView methods directly on the Items property and the ItemCollection class will delegate the call to the appropriate underlying collection view.</p>
<p><strong>How it Works</strong></p>
<p>In practice, the properties of an &#8220;editable&#8221; object will rarely be updated directly in code behind. Rather, these properties will be updated via bindings to properties on controls within the UI.</p>
<p>In WPF, it is fairly common to present data using a <em>&#8220;view template&#8221;</em>. Such a template will often present a readonly view of the data using elements like TextBlock, Image, etc. Then, when it is necessary to edit the data, the view will switch to an <em>&#8220;edit template&#8221;</em> that contains editable controls like TextBox, ComboBox, CheckBox, etc.</p>
<p>The IEditableObject interface provides three transactional methods: BeginEdit(), CancelEdit(), and EndEdit(). I prefer to expose an additional readonly property on the editable object called IsInEditMode that can be used as a trigger for swapping between the view template and the edit template.</p>
<p>Below is my typical implementation of IEditableObject, as it would be implemented on the Character class in our example:</p>
<pre><span style="font-family: Courier New;"><span style="color: #0000ff;">    #region</span> IEditableObject support
</span><span style="font-family: Courier New;"><span style="color: #0000ff;">
    public</span> <span style="color: #008080;">Character</span> _cachedCopy = <span style="color: #0000ff;">null</span>;

</span><span style="font-family: Courier New;"><span style="color: #0000ff;">    public void</span> BeginEdit()
    {
        <span style="color: #009933;">// save object state before entering edit mode
</span>        _cachedCopy = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Character</span>();
        _cachedCopy._first = _first;
        _cachedCopy._last = _last;
        _cachedCopy._image = _image;
        _cachedCopy._gender = _gender;

</span><span style="font-family: Courier New;">        <span style="color: #009933;">// ensure edit mode flag is set
</span>        IsInEditMode = <span style="color: #0000ff;">true</span>;
    }

</span><span style="font-family: Courier New;"><span style="color: #0000ff;">    public void</span> CancelEdit()
    {
        <span style="color: #009933;">// restore original object state
</span>        <span style="color: #0000ff;">if</span> (_cachedCopy != <span style="color: #0000ff;">null</span>)
        {
            First = _cachedCopy._first;
            Last = _cachedCopy._last;
            Image = _cachedCopy._image;
            Gender = _cachedCopy._gender;
        }

</span><span style="font-family: Courier New;">        <span style="color: #009933;">// clear cached data
</span>        _cachedCopy = <span style="color: #0000ff;">null</span>;

</span><span style="font-family: Courier New;">        <span style="color: #009933;">// ensure edit mode flag is unset
</span>        IsInEditMode = <span style="color: #0000ff;">false</span>;
    }

</span><span style="font-family: Courier New;"><span style="color: #0000ff;">    public void</span> EndEdit()
    {
        <span style="color: #009933;">// clear cached data
</span>        _cachedCopy = <span style="color: #0000ff;">null</span>;

</span><span style="font-family: Courier New;">        <span style="color: #009933;">// ensure edit mode flag is unset
</span>        IsInEditMode = <span style="color: #0000ff;">false</span>;
    }

</span><span style="font-family: Courier New;"><span style="color: #0000ff;">    private bool</span> _isInEditMode = <span style="color: #0000ff;">false</span>;
<span style="color: #0000ff;">    public bool</span> IsInEditMode
    {
        <span style="color: #0000ff;">get</span> { <span style="color: #0000ff;">return</span> _isInEditMode; }
        <span style="color: #0000ff;">private set</span>
        {
            if (_isInEditMode != <span style="color: #0000ff;">value</span>)
            {
                _isInEditMode = <span style="color: #0000ff;">value</span>;
                RaisePropertyChanged(<span style="color: #993300;">"IsInEditMode"</span>);
            }
        }
    }

</span><span style="font-family: Courier New; color: #0000ff;">    #endregion</span></pre>
<p><strong><a class="FCK__AnchorC" name="DownloadTheSample"></a>Download the Sample</strong></p>
<p>You can <a href="http://drwpf.com/blog/Portals/0/Samples/EditableCollectionSample.zip">download the complete sample</a> for this post to see the IEditableObject and IEditableCollectionView interfaces in action. When you run the sample, simply double-click an item (or press F2) to enter edit mode.</p>
<p><img src="http://drwpf.com/blog/Portals/0/Images/ItemsControl/E/EditModeTemplate.jpg" alt="" /></p>
<p>If you do not wish to commit your changes, press Escape. If you do wish to commit your changes, press Enter or simply select another character. When the changes are committed, you will notice that the item immediately moves to its proper location within the view.</p>
<p><strong>Is IEditableObject Absolutely Required?</strong></p>
<p>You posed the question, <em>&#8220;What would you suggest I do if I have a collection of a type that I don&#8217;t know about at compile time?&#8221;</em></p>
<p>First, I would advise you to avoid that situation if at all possible. The model-view-viewmodel pattern typically involves wrapping or replicating items (and collections) of known types within observable classes (classes that provide change notifications like INotifyPropertyChanged and INotifyCollectionChanged) and adding additional interfaces (like IEditableObject) to either the data model objects or the viewmodel objects to allow them to play nicely with the view. That is always my preferred approach.</p>
<p>Having said that, there are certainly times when you may not have the option of modifying the entity within your collection. If you simply cannot add the IEditableObject interface to the data model or viewmodel class, you needn&#8217;t fret. The IEditableCollectionView interface is still your friend (as long as you are targeting .NET 3.5 SP1, of course). You won&#8217;t get all of the transactional goodness of IEditableObject, but you can still call EditItem() followed by CommitEdit() to update the view&#8217;s notion of a specific item.</p>
<p>Consider the earlier example where the characters were not correctly sorted or grouped after changing Bart&#8217;s name and gender. It turns out that you can simply add the lines below to cause that specific item to be moved to the correct location within the view:</p>
<pre><span style="font-family: Courier New;">    <span style="color: #008080;">Character </span>bart = lb.Items[0] <span style="color: #0000ff;">as</span> <span style="color: #008080;">Character</span>;
    bart.First = <span style="color: #993300;">"Mandy"</span>;
    bart.Gender = <span style="color: #008080;">Gender</span>.Female;
    (lb.Items <span style="color: #0000ff;">as</span> <span style="color: #008080;">IEditableCollectionView</span>).EditItem(bart);
    (lb.Items <span style="color: #0000ff;">as</span> <span style="color: #008080;">IEditableCollectionView</span>).CommitEdit();</span></pre>
<p>Voîla! There is no longer a need to explicitly refresh the entire view!</p>
<p><strong>Order now and receive these bonus gifts!</strong></p>
<p>The <a href="http://drwpf.com/blog/Portals/0/Samples/EditableCollectionSample.zip">downloadable sample</a> included with this post covers the specific questions posed by Patient-X, but there is more to IEditableCollectionView. It also provides a convenient way to add and commit new items to the source collection. You can even use it to remove existing items from the source collection. By leveraging members of the IEditableCollectionView interface for such changes, you can ensure that your view of the collection will remain accurate with respect to grouping, sorting, and filtering.</p>
<p>To see some of the other features of IEditableCollectionView, check out <a href="http://blogs.msdn.com/vinsibal/archive/2008/05/20/wpf-3-5-sp1-feature-ieditablecollectionview.aspx" target="_blank">Vincent Sibal&#8217;s introduction to IEditableCollectionView</a>, He also includes a nice code sample with his post.</p>
<p>Cheers,<br />
Dr. WPF</p>
<p>P.S. For anyone who is hoping to get a published response to a WPF question, you should note (as Patient-X has) that the doctor is easily manipulated by wordsmithery. If you use lots of obscure terms like <em>serein</em> and <em>hey rube</em>, there is a much greater chance you will receive a public response, as it appeals to my invented persona&#8217;s inflated sense of perspicacity! <img src='http://drwpf.com/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </div>
]]></content:encoded>
			<wfw:commentRss>http://drwpf.com/blog/2008/10/20/itemscontrol-e-is-for-editable-collection/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>ItemsControl: &#039;C&#039; is for Collection</title>
		<link>http://drwpf.com/blog/2007/11/05/itemscontrol-c-is-for-collection/</link>
		<comments>http://drwpf.com/blog/2007/11/05/itemscontrol-c-is-for-collection/#comments</comments>
		<pubDate>Mon, 05 Nov 2007 23:06:27 +0000</pubDate>
		<dc:creator>Dr. WPF</dc:creator>
				<category><![CDATA[Collections]]></category>
		<category><![CDATA[ItemsControl]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://drwpf.com/blog/?p=18</guid>
		<description><![CDATA[
The series continues&#8230;
An ItemsControl would be nothing without its collection of Items. In this post, we investigate the &#8220;Items&#8221; of an ItemsControl, looking at each of the following areas:

The Items Collection
Item Collection Modes
Observable Collections
CollectionView: &#8220;The Great Equalizer&#8221;
Performance Considerations
Items and the Element Trees

If I were rating the technical level of each post in this series, I [...]]]></description>
			<content:encoded><![CDATA[<div class="jbr">
<p>The <a title="ItemsControl: A to Z" href="http://drwpf.com/blog/?p=13" target="_blank">series</a> continues&#8230;</p>
<p>An ItemsControl would be nothing without its collection of <em>Items</em>. In this post, we investigate the &#8220;Items&#8221; of an ItemsControl, looking at each of the following areas:</p>
<ul>
<li><a href="#ItemCollection">The Items Collection</a></li>
<li><a href="#ItemCollectionModes">Item Collection Modes</a></li>
<li><a href="#ObservableCollections">Observable Collections</a></li>
<li><a href="#CollectionView">CollectionView: <em>&#8220;The Great Equalizer&#8221;</em></a></li>
<li><a href="#Performance">Performance Considerations</a></li>
<li><a href="#ElementTrees">Items and the Element Trees</a></li>
</ul>
<p>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 <img src='http://drwpf.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ).</p>
<p><strong><a name="ItemCollection"></a>The Items Collection (a.k.a, the <em>ItemCollection</em>) </strong></p>
<p>The &#8220;Items&#8221; property of an ItemsControl provides access to a collection of objects, or <em>data items</em>, that make up the logical content of the control. The type of this property is ItemCollection. (I will use the terms &#8220;Items collection&#8221; and &#8220;ItemCollection&#8221; interchangeably.) The &#8220;Type&#8221; of each item within the Items collection is Object. So literally <em>any </em>CLR object can be added to an ItemCollection.</p>
<p>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.</p>
<p>1) The Items property is a read-only CLR property.</p>
<p>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.</p>
<p>2) The Items property is <em><strong>not </strong></em>backed by a dependency property.</p>
<p>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 <em>direct</em>) scenario&#8230;</p>
<p><strong><a name="ItemCollectionModes"></a>ItemCollection Modes: Direct and ItemsSource</strong></p>
<p>Although the Items property is read only, the provided collection is not necessarily read only. In fact, in earlier posts, we&#8217;ve already seen that you can directly add items to an ItemsControl:</p>
<pre><span style="font-family: Courier New;">&lt;<span style="color: #993300;">ListBox</span>&gt;
</span>  &lt;<span style="color: #993300;">sys:String</span>&gt;Item 1&lt;/<span style="color: #993300;">sys:String</span>&gt;
  &lt;<span style="color: #993300;">sys:String</span>&gt;Item 2&lt;/<span style="color: #993300;">sys:String</span>&gt;
  &lt;<span style="color: #993300;">sys:String</span>&gt;Item 3&lt;/<span style="color: #993300;">sys:String</span>&gt;
&lt;/<span style="color: #993300;">ListBox</span>&gt;</pre>
<p>Because items are added <em>directly</em> to the ListBox, this is an example of using an ItemCollection in <em>&#8220;direct mode&#8221;</em>. 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.</p>
<p>The other mode for an ItemCollection is called <em>&#8220;ItemsSource mode&#8221;</em>. In ItemsSource mode, the items in the ItemCollection correspond to <em>items</em> in a <em>source</em> collection. That source collection is specified via a separate property on the ItemsControl that is appropriately named &#8220;ItemsSource&#8221;.</p>
<p>The following shows a typical scenario of an ItemsControl using ItemsSource mode:</p>
<pre><span style="font-family: Courier New;">&lt;<span style="color: #993300;">ListView</span> <strong><span style="color: #ff0000;">ItemsSource</span>="{Binding Path=Characters}"</strong>&gt;
</span>  &lt;<span style="color: #993300;">ListView.View</span>&gt;
    &lt;<span style="color: #993300;">GridView</span>&gt;
      &lt;<span style="color: #993300;">GridViewColumn</span> <span style="color: #ff0000;">Width</span>="100"
        <span style="color: #ff0000;">DisplayMemberBinding</span>="{Binding Last}"
        <span style="color: #ff0000;">Header</span>="Last Name" /&gt;
      &lt;<span style="color: #993300;">GridViewColumn</span> <span style="color: #ff0000;">Width</span>="100"
        <span style="color: #ff0000;">DisplayMemberBinding</span>="{Binding First}"
        <span style="color: #ff0000;">Header</span>="First Name" /&gt;
      &lt;<span style="color: #993300;">GridViewColumn</span> <span style="color: #ff0000;">Width</span>="60"
        <span style="color: #ff0000;">DisplayMemberBinding</span>="{Binding Gender}"
        <span style="color: #ff0000;">Header</span>="Gender" /&gt;
    &lt;/<span style="color: #993300;">GridView</span>&gt;
  &lt;/<span style="color: #993300;">ListView.View</span>&gt;
&lt;/<span style="color: #993300;">ListView</span>&gt;</pre>
<p>The ItemsSource property is a dependency property of type IEnumerable. This tells us two important things:</p>
<p>1) The source collection can be <em>any</em> enumerable collection.</p>
<p>2) The ItemsSource property can be established using a binding.</p>
<p>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.</p>
<p><em>Sidenote:</em> 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:</p>
<pre><span style="font-family: Courier New;">&lt;<span style="color: #993300;">ListBox </span><strong><span style="color: #ff0000;">ItemsSource</span>="{StaticResource Characters}"</strong> /&gt;</span></pre>
<p><strong>The Modes are Mutually Exclusive</strong></p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p><strong><a name="ObservableCollections"></a>Observable Collections Support Dynamic Updates</strong></p>
<p>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.</p>
<p><em>But what about dynamic collection changes in ItemsSource mode? How could the Items collection possibly know about changes to the source collection?</em></p>
<p>The answer is that the ItemCollection <em>cannot</em> know about any such changes unless the source collection chooses to announce those changes by providing <em>change notifications</em>. 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 <em>observable</em>.</p>
<p>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.</p>
<p>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&lt;T&gt;. By creating an instance of this class, you automatically get all of the change notifications without having to do any extra work.</p>
<p>Typically, you will see a collection class derive from ObservableCollection&lt;T&gt;, to create a strongly typed collection, as follows:</p>
<pre><span style="font-family: Courier New;"><span style="color: #0000ff;">    public class</span> <span style="color: #339966;">StringCollection</span> : <span style="color: #339966;">ObservableCollection</span>&lt;<span style="color: #0000ff;">string</span>&gt;
</span>    {
    }</pre>
<p>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 <span style="font-family: Courier New;"><span style="color: #339966;">Collection</span>&lt;<span style="color: #0000ff;">string</span>&gt;</span>.</p>
<p><em>So what if the collection is not observable? Can it still serve as an ItemsSource? </em></p>
<p>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.</p>
<p><strong><a name="CollectionView"></a>CollectionView: <em>&#8220;The Great Equalizer&#8221;</em></strong></p>
<p>If you&#8217;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 <em>currency</em>, which means a CollectionView maintains a <em>current item</em> pointer that can be accessed and moved using methods on the CollectionView.</p>
<p>Every enumerable collection in WPF has a <em>default</em> 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:</p>
<pre><span style="font-family: Courier New;">&lt;<span style="color: #993300;">CollectionViewSource</span> <span style="color: #ff0000;">x:Key</span>="characterView"</span>
    <span style="color: #ff0000;">Source</span>="{StaticResource Characters} "&gt;
  &lt;<span style="color: #993300;">CollectionViewSource.SortDescriptions</span>&gt;
    &lt;<span style="color: #993300;">componentModel:SortDescription</span> <span style="color: #ff0000;">PropertyName</span>="First" /&gt;
  &lt;/<span style="color: #993300;">CollectionViewSource.SortDescriptions</span>&gt;
  &lt;<span style="color: #993300;">CollectionViewSource.GroupDescriptions</span>&gt;
    &lt;<span style="color: #993300;">dat:PropertyGroupDescription</span> <span style="color: #ff0000;">PropertyName</span>="Last" /&gt;
  &lt;/<span style="color: #993300;">CollectionViewSource.GroupDescriptions</span>&gt;
&lt;/<span style="color: #993300;">CollectionViewSource</span>&gt;</pre>
<p>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.</p>
<p><em>&#8220;But Dad, I don&#8217;t WANT a CollectionView!&#8221;</em></p>
<p>&#8220;I didn&#8217;t ask what you WANT&#8230; As long as you&#8217;re living under my roof, you&#8217;ll use a CollectionView!&#8221;</p>
<p>With WPF, sometimes it&#8217;s not as much about what you <em>want</em>, as it is about what the framework <em>needs</em>. 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.</p>
<p>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&lt;T&gt; class that provides no such notifications.</p>
<p>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&#8230; if it&#8217;s an observable collection, do this, or if it&#8217;s an IList, do this, or if it&#8217;s an IEnumerable, do this, etc.</p>
<p><em>Enter the CollectionView class&#8230;</em></p>
<p>To deal with this challenge of disparate collections, WPF introduces the CollectionView class to serve as <em>the great equalizer</em> of enumerable collections. It is the CollectionView class that internally looks at a collection&#8217;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.</p>
<p>So whether or not you care about currency, grouping, sorting, filtering, change notifications, etc., the Items collection of an ItemsControl is <em>always</em> maintained internally using a CollectionView. In fact, the ItemCollection class <em>is </em>a CollectionView.</p>
<p>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.</p>
<p><em>So you&#8217;re observable&#8230; Who cares?</em></p>
<p>CollectionView does. We&#8217;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&#8217;ve ever wondered exactly who is monitoring these events, get a life! Sorry&#8230; I meant to say, it&#8217;s CollectionView. Now you know.</p>
<p><strong><a name="Performance"></a>Performance Considerations around Bound Collections</strong></p>
<p>Keeping in mind that CollectionView serves as the great equalizer of collections, we should look at some performance considerations around binding to collections. We&#8217;ve already acknowledged that not all collections support the same features. Often, CollectionView must perform extra work to support its common interface for collections.</p>
<p>One of the major features provided by CollectionView is <em>indexing</em> 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().</p>
<p>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&lt;T&gt; implements IList, so it&#8217;s a great choice.</p>
<p>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.</p>
<p>So the key perf takeaway is that the source collection should support IList whenever possible.</p>
<p><strong><a name="ElementTrees"></a>Items and the Element Trees</strong></p>
<p>The items within the Items collection make up the logical children of the ItemsControl. They are said to be members of the <em>logical tree</em>. For a HeaderedItemsControl, the headers associated with each item will also be logical children of the ItemsControl. (Btw, if you&#8217;re not sure what a HeaderedItemsControl is, you should revisit <em>&#8220;<a href="http://theiridescentthong.drwpf.com/ICIQ/" target="_blank">The ICIQ Test</a>&#8220;</em> and spend a little more time exploring the tooltips after receiving your score.)</p>
<p>If the items in the Items collection happen to be visuals, then they will also be members of the <em>visual tree</em>. 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 <em>DataTemplate</em>. For more on that, please tune in for the next episode in this series&#8230; <em><strong>&#8216;D&#8217; is for DataTemplate</strong></em>.</div>
]]></content:encoded>
			<wfw:commentRss>http://drwpf.com/blog/2007/11/05/itemscontrol-c-is-for-collection/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
	</channel>
</rss>
