title: Binding an ObservableCollection to an ItemsControl - not as simple as it sounds?
body: <p>This has been very difficult to track down and has caused me a great deal of pain - but it seems <code>ItemsControls</code> do not behave the way I would expect. It almost seems like a bug in WPF - but being new to WPF I'm erring on the side of it's my fault, not theirs.</p>
  
  <p>To reproduce it is very simple - bind an <code>ItemsControl</code> to an <code>ObservableCollection</code>, and then replace an item in the collection. It's so simple I cannot believe Google doesn't find thousands of people with the same problem.</p>
  
  <p>The code below simply binds an <code>ItemsControl</code> to an <code>ObservableCollection</code> of <code>Brush</code>. Change a brush (by clicking the button), and you get a couple of data errors as the rectangle's brush binding is momentarily of the <code>DataContext</code> of the <code>ItemsControl</code> (!), rather than of the new item. This momentary crash of bindings has caused my application to take over half a second to update when run in the debugger whenever I replace an (immutable, regular CLR object) item in the collection - what am I doing wrong?</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;Window x:Class="Dummy.Test"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Title="Test" Height="300" Width="300"&gt;
      &lt;Grid&gt;
          &lt;ItemsControl ItemsSource="{Binding Foos}"&gt;
              &lt;ItemsControl.ItemTemplate&gt;
                  &lt;DataTemplate DataType="{x:Type Brush}"&gt;
                      &lt;Rectangle Width="20" Height="20" Fill="{Binding}" /&gt;
                  &lt;/DataTemplate&gt;
              &lt;/ItemsControl.ItemTemplate&gt;
          &lt;/ItemsControl&gt;
          &lt;Button HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="SwitchClick"&gt;Switch&lt;/Button&gt;
      &lt;/Grid&gt;
  &lt;/Window&gt;
  </code></pre>
  
  <pre class="lang-cs prettyprint-override"><code>using System;
  using System.Collections.ObjectModel;
  using System.Windows;
  using System.Windows.Media;
  
  namespace Dummy
  {
      public partial class Test : Window
      {
          private readonly ObservableCollection&lt;Brush&gt; foos = new ObservableCollection&lt;Brush&gt;();
          public ObservableCollection&lt;Brush&gt; Foos { get { return foos; } }
          public Test()
          {
              InitializeComponent();
              Foos.Add(Brushes.Green);
              DataContext = this;
          }
  
          private void SwitchClick(object sender, EventArgs e)
          {
              Foos[0] = Foos[0] == Brushes.Green ? Brushes.Silver : Brushes.Green;
          }
      }
  }
  </code></pre>