title: "Specified argument was out of the range of valid values.Parameter name: index" when adding new item to ObservableCollection<T>
body: <p>I get a such exception:</p>
  
  <blockquote>
    <p>'FooStorageStorage.Add(new TreeViewItem() { Header=i.ToString()})'
    threw an exception of type 'System.ArgumentOutOfRangeException':
    "Specified argument was out of the range of valid values.\r\nParameter
    name: index"</p>
  </blockquote>
  
  <p>I have a property in viewModel:</p>
  
  <pre><code>private ObservableCollection&lt;TreeViewItem&gt; fooStorage=new ObservableCollection&lt;TreeViewItem&gt;();
  public ObservableCollection&lt;TreeViewItem&gt; FooStorage
  {
     get { return facetStorage; }
     set { facetStorage = value; }
  }
  </code></pre>
  
  <p>However, after I cleared <code>FooStorage</code> and trying to add new item:</p>
  
  <pre><code>private void LoadData()
  {
      if (FooStorage.Count &gt; 0)
      {
         FooStorage.Clear();
      }
      for (int k = 0; k &lt; lengthOfColl; k++)            
      {
         FooStorage.Add(new TreeViewItem() { Header=k.ToString()});//here is exception
      }
  }
  </code></pre>
  
  <p>I've got an above exception.</p>
  
  <p>When I call a method LoadData() at the first time, it all works okay. Then if I call a method LoadData() at the second time, then I get a such exception.</p>
  
  <p>Have anybody met a such exception? The most interesting thing that I cannot reproduce this exception in a test project.</p>
  
  <p>StackTrace:</p>
  
  <blockquote>
    <p>System.ArgumentOutOfRangeException was unhandled   HResult=-2146233086
    Message=Specified argument was out of the range of valid values.
    Parameter name: index   ParamName=index   Source=PresentationCore<br>
    StackTrace:
           at System.Windows.Media.VisualCollection.Insert(Int32 index, Visual visual)
           at System.Windows.Controls.UIElementCollection.InsertInternal(Int32
    index, UIElement element)
           at System.Windows.Controls.Panel.AddChildren(GeneratorPosition pos, Int32 itemCount)
           at System.Windows.Controls.Panel.OnItemsChangedInternal(Object sender, ItemsChangedEventArgs args)
           at System.Windows.Controls.Panel.OnItemsChanged(Object sender, ItemsChangedEventArgs args)
           at System.Windows.Controls.ItemContainerGenerator.OnItemAdded(Object
    item, Int32 index)
           at System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object
    sender, NotifyCollectionChangedEventArgs args)
           at System.Windows.WeakEventManager.ListenerList<code>1.DeliverEvent(Object
    sender, EventArgs e, Type managerType)
           at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
           at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object
    sender, NotifyCollectionChangedEventArgs args)
           at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object
    sender, NotifyCollectionChangedEventArgs e)
           at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs
    args)
           at System.Windows.Controls.ItemCollection.OnViewCollectionChanged(Object
    sender, NotifyCollectionChangedEventArgs e)
           at System.Windows.WeakEventManager.ListenerList</code>1.DeliverEvent(Object
    sender, EventArgs e, Type managerType)
           at System.Windows.WeakEventManager.DeliverEvent(Object sender, EventArgs args)
           at System.Collections.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object
    sender, NotifyCollectionChangedEventArgs args)
           at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs
    args)
           at System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs
    args, Int32 adjustedOldIndex, Int32 adjustedNewIndex)
           at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs
    args)
           at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender,
    NotifyCollectionChangedEventArgs args)
           at System.Collections.ObjectModel.ObservableCollection<code>1.OnCollectionChanged(NotifyCollectionChangedEventArgs
    e)
           at System.Collections.ObjectModel.ObservableCollection</code>1.InsertItem(Int32
    index, T item)
           at System.Collections.ObjectModel.Collection<code>1.Add(T item)
           at ModuleA.ViewModel.PersonControlViewModel.LoadData(IPerson person) in D:\WPF\...\ViewModel\PersonControlViewModel.cs:line 110
           at Prism.Commands.DelegateCommand</code>1.&lt;>c__DisplayClass1_0.&lt;.ctor>b__0(Object
    o)
           at Prism.Commands.DelegateCommandBase.&lt;>c__DisplayClass5_0.&lt;.ctor>b__0(Object
    arg)
           at Prism.Commands.DelegateCommandBase.d__14.MoveNext()
        --- End of stack trace from previous location where exception was thrown ---
           at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
    task)
           at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
    task)
           at Prism.Commands.DelegateCommandBase.d__12.MoveNext()
        --- End of stack trace from previous location where exception was thrown ---
           at System.Runtime.CompilerServices.AsyncMethodBuilderCore.&lt;>c.b__6_0(Object
    state)
           at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
    callback, Object args, Int32 numArgs)
           at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
    Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
           at System.Windows.Threading.DispatcherOperation.InvokeImpl()
           at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object
    state)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext
    executionContext, ContextCallback callback, Object state, Boolean
    preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
    preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext
    executionContext, ContextCallback callback, Object state)
           at System.Windows.Threading.DispatcherOperation.Invoke()
           at System.Windows.Threading.Dispatcher.ProcessQueue()
           at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
           at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
           at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
           at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
    callback, Object args, Int32 numArgs)
           at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source,
    Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
           at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
    priority, TimeSpan timeout, Delegate method, Object args, Int32
    numArgs)
           at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
           at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg)
           at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame
    frame)
           at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
           at System.Windows.Application.RunDispatcher(Object ignore)
           at System.Windows.Application.RunInternal(Window window)
           at System.Windows.Application.Run(Window window)
           at System.Windows.Application.Run()
           at PrototypeBootstrapper.App.Main() in D:\WPF...\Src\PrototypeBootstrapper\obj\Debug\App.g.cs:line 0
           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext
    executionContext, ContextCallback callback, Object state, Boolean
    preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean
    preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()   InnerException:</p>
  </blockquote>
  
  <p><strong>Update:</strong></p>
  
  <p>I am adding new <code>TreeViewItem's</code> from <code>FooStorage</code> to different <code>TreeView</code> placed inside of HeaderTemplate of <code>DataGridTextBoxColumn</code>. So when user clicks at <code>Header1</code> of <code>DataGridTextBoxColumn2</code>, then <code>TreeView</code> of <code>Header1</code> is populated by <code>FooStorage</code> from viewModel. OK. The when user clicks at <code>Header2</code> of <code>DataGridTextBoxColumn2</code>, then <code>TreeView</code> of <code>Header2</code> should be populated by <code>FooStorage</code> from viewModel, however when I <code>Clear()</code> and <code>Add()</code> new items to <code>FooStorage</code>, then I've got an above exception.</p>