title: Unable to cast object of type 'MS.Internal.NamedObject' to custom type
body: <p>I am not new to WPF, but I can't figure out this problem:</p>
  
  <p>I use an <code>ObservableCollection&lt;MyCustomType&gt;</code> that i bind to <code>ComboBox</code>es, it's all working great as usual, but at some point i need to change the content of the collection (i retrieve a new set from the database, that may or may not contain part of the old one).</p>
  
  <p>Now adding or removing elements is all done by WPF, but if you change the whole collection I found you had to raise PropertyChanged for the collection.</p>
  
  <p>The problem is that <em>sometimes</em> it crashes giving me a not-so-friendly exception.<br>
  I'm unsure of what exactly triggers the crash, but if I don't touch the View and retrieve a new set from DB, it doesn't crash.<br></p>
  
  <p>Here is some code:</p>
  
  <pre><code>    public const string MyObsCollectionProperty = "MyObsCollection";
      private ObservableCollection&lt;MyCustomType&gt; m_MyObsCollection;
      public ObservableCollection&lt;MyCustomType&gt; MyObsCollection
      {
          get { return m_MyObsCollection; }
          set
          {
              m_MyObsCollection = value;
              RaisePropertyChanged(MyObsCollectionProperty); // &lt;-- Crashes here
          }
      }
  </code></pre>
  
  <p>I get the exception: <code>Unable to cast object of type 'MS.Internal.NamedObject' to type 'MyNameSpace.MyCustomType'</code></p>
  
  <p>Please note that this exception comes from Prism, but it's probably just because i inherit from NotificationObject on my ViewModel.</p>
  
  <p>I appreciate any help on this problem,</p>
  
  <p>Regards, </p>
  
  <p>LK.</p>
  
  <p><strong>EDIT:</strong> I think the problem comes from the ComboBox, and more specifically, from the way i set their properties.</p>
  
  <p>I bind the ItemsSource property to an ObservableCollection, and to decide which element to select, I bind the SelectedValue to a field of an item of an ObservableCollection (the ComboBox is nested within a ListView).<br>
  I also set SelectedValuePath (you get the idea).</p>
  
  <p>I guess when i change the first collection hell breaks lose on that setup. And it leaves it in peace when i don't touch the view because of virtualization (it is hidden at first).</p>
  
  <p><strong>ADDITION:</strong></p>
  
  <p>The InnerException is nulll. </p>
  
  <p><em>Message:</em> <code>Unable to cast object of type 'MS.Internal.NamedObject' to type 'CocoonV4.DAL.WcfServiceCocoonV4.DekoTemplate'.</code> </p>
  
  <pre><code>   at Microsoft.Practices.Prism.Commands.DelegateCommand`1.&lt;&gt;c__DisplayClass6.&lt;.ctor&gt;b__3(Object o)
     at Microsoft.Practices.Prism.Commands.DelegateCommandBase.CanExecute(Object parameter)
     at Microsoft.Practices.Prism.Commands.DelegateCommandBase.System.Windows.Input.ICommand.CanExecute(Object parameter)
     at System.Windows.Interactivity.InvokeCommandAction.Invoke(Object parameter)
     at System.Windows.Interactivity.TriggerBase.InvokeActions(Object parameter)
     at System.Windows.Interactivity.EventTriggerBase.OnEvent(EventArgs eventArgs)
     at System.Windows.Interactivity.EventTriggerBase.OnEventImpl(Object sender, EventArgs eventArgs)
     at System.Windows.Controls.SelectionChangedEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
     at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
     at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
     at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
     at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
     at System.Windows.Controls.ComboBox.OnSelectionChanged(SelectionChangedEventArgs e)
     at System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(List`1 unselectedItems, List`1 selectedItems)
     at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
     at System.Windows.Controls.Primitives.Selector.OnItemsChanged(NotifyCollectionChangedEventArgs e)
     at System.Windows.Controls.ItemsControl.OnItemCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
     at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Controls.ItemCollection.System.Windows.IWeakEventListener.ReceiveWeakEvent(Type managerType, Object sender, EventArgs e)
     at System.Windows.WeakEventManager.DeliverEventToList(Object sender, EventArgs args, ListenerList list)
     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.RefreshOverride()
     at System.Windows.Data.CollectionView.RefreshOrDefer()
     at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)
     at System.Windows.Data.CollectionView.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
     at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
     at System.Collections.ObjectModel.ObservableCollection`1.ClearItems()
     at System.Collections.ObjectModel.Collection`1.Clear()
     at CocoonV4.Modules.CocoonViewsVMs.ManageTemplateDekocastViewModel.SetAllowedDekos(IEnumerable`1 _NewAllowedDekos) in C:\Users\lkottmann\Documents\Visual Studio 2010\Projects\IAV-Cocoon\MAIN\CocoonV4\CocoonV4.Modules.RunningItem\CocoonViewsVMs\ManageTemplateDekocastViewModel.cs:line 83
     at CocoonV4.Modules.CocoonViewsVMs.ManageTemplateDekocastViewModel.LoadTemplates(Nullable`1 param) in C:\Users\lkottmann\Documents\Visual Studio 2010\Projects\IAV-Cocoon\MAIN\CocoonV4\CocoonV4.Modules.RunningItem\CocoonViewsVMs\ManageTemplateDekocastViewModel.cs:line 128
     at Microsoft.Practices.Prism.Commands.DelegateCommand`1.&lt;&gt;c__DisplayClass6.&lt;.ctor&gt;b__2(Object o)
     at Microsoft.Practices.Prism.Commands.DelegateCommandBase.Execute(Object parameter)
     at Microsoft.Practices.Prism.Commands.DelegateCommandBase.System.Windows.Input.ICommand.Execute(Object parameter)
     at System.Windows.Interactivity.InvokeCommandAction.Invoke(Object parameter)
     at System.Windows.Interactivity.TriggerBase.InvokeActions(Object parameter)
     at System.Windows.Interactivity.EventTriggerBase.OnEvent(EventArgs eventArgs)
     at System.Windows.Interactivity.EventTriggerBase.OnEventImpl(Object sender, EventArgs eventArgs)
     at System.Windows.Controls.SelectionChangedEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
     at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
     at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
     at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
     at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
     at System.Windows.Controls.ComboBox.OnSelectionChanged(SelectionChangedEventArgs e)
     at System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(List`1 unselectedItems, List`1 selectedItems)
     at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
     at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(Object item, Boolean assumeInItemsCollection)
     at System.Windows.Controls.ComboBox.NotifyComboBoxItemMouseUp(ComboBoxItem comboBoxItem)
     at System.Windows.Controls.ComboBoxItem.OnMouseLeftButtonUp(MouseButtonEventArgs e)
     at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
     at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
     at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
     at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
     at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
     at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
     at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
     at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
     at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
     at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
     at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
     at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
     at System.Windows.Input.InputManager.ProcessStagingArea()
     at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
     at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
     at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
     at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
     at System.Windows.Interop.HwndSource.InputFilterMessage(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 MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
     at System.Windows.Threading.Dispatcher.InvokeImpl(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 CocoonV4.App.Main() in C:\Users\lkottmann\Documents\Visual Studio 2010\Projects\IAV-Cocoon\MAIN\CocoonV4\CocoonV4\obj\x86\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.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
     at System.Threading.ThreadHelper.ThreadStart()
  </code></pre>
  
  <p><strong>More EDIT:</strong></p>
  
  <p>I isolated the problem to a single ComboBox declarated as follow:</p>
  
  <pre><code>&lt;custom:CComboBox x:Name="cmbFirstDko"
                    ItemsSource="{Binding Path=DataContext.MyFirstCollection, ElementName=myViewName}"
                    SelectedValue="{Binding anObjectID, Mode=TwoWay}"
                    SelectedValuePath="anObjectID"&gt;
  </code></pre>
  
  <p>Please note that the <code>anObjectID</code> property in <code>SelectedValue</code> comes from the <code>ListView</code>'s DataContext (this ComboBox is displaying part of an item of that ListView), whereas the <code>anObjectID</code> in <code>SelectedValuePath</code> refers to a property that each item in <code>DataContext.MyFirstCollection</code> has.</p>
  
  <p>This allows me to select a different ComboBoxItem for each element of the ListView.</p>
  
  <p>I hope my explanation is clear, otherwise tell me in the comments and i'll try to clarify.</p>
  
  <p><strong>Breakthrough:</strong>
  The ComboBoxes have their DataContext set to {DisconnectedItem}, this is the result of the work of so-called SentinelObjects which intervene when there's a binding between 2 collections, as in my example.</p>
  
  <p>It is actually officialy a bug of the framework, and it has been fixed for the next version, see this <a href="https://connect.microsoft.com/VisualStudio/feedback/details/619658/wpf-virtualized-control-disconnecteditem-reference-when-datacontext-switch">MS Bug Page</a></p>
  
  <p>Does anyone know of a workaround?</p>
  
  <p><strong>EDIT:</strong>
  There used to be an answer linking to my blog, but while I move it people downvoted the answer. I got sick of it so now it'll be back when it's ready.</p>