2011-11-22 84 views
15

no soy nuevo en WPF, pero no puedo averiguar este problema:No se puede convertir objeto de tipo 'MS.Internal.NamedObject' a medida Tipo

utilizo un ObservableCollection<MyCustomType> que se unen a ComboBox ES , todo funciona bien, como siempre, pero en algún momento tengo que cambiar el contenido de la colección (obtengo un nuevo conjunto de la base de datos, que puede contener o no parte del anterior).

Ahora, agregar o eliminar elementos lo hace todo WPF, pero si cambias toda la colección que encontré, debes subir PropertyChanged para la colección.

El problema es que a veces se bloquea al darme una excepción no tan amistosa.
No estoy seguro de qué desencadena exactamente el bloqueo, pero si no toco la Vista y recupero un nuevo conjunto de DB, no se bloquea.

Aquí hay un código:

public const string MyObsCollectionProperty = "MyObsCollection"; 
    private ObservableCollection<MyCustomType> m_MyObsCollection; 
    public ObservableCollection<MyCustomType> MyObsCollection 
    { 
     get { return m_MyObsCollection; } 
     set 
     { 
      m_MyObsCollection = value; 
      RaisePropertyChanged(MyObsCollectionProperty); // <-- Crashes here 
     } 
    } 

consigo la excepción: Unable to cast object of type 'MS.Internal.NamedObject' to type 'MyNameSpace.MyCustomType'

Tenga en cuenta que esta excepción viene de la prisma, pero es probable que sólo porque yo heredar de NotificationObject en mi modelo de vista.

Agradezco cualquier ayuda en este problema,

Saludos,

LK.

EDIT: Creo que el problema proviene del ComboBox, y más específicamente, de la forma en que establezco sus propiedades.

Enlazo la propiedad ItemsSource a una ObservableCollection, y para decidir qué elemento seleccionar, enlazo el SelectedValue a un campo de un elemento de un ObservableCollection (el ComboBox está anidado dentro de un ListView).
También configuré SelectedValuePath (se entiende).

Supongo que cuando cambie la primera colección, se rompe el infierno en esa configuración. Y lo deja en paz cuando no toco la vista debido a la virtualización (está oculta al principio).

ADEMÁS:

El InnerException es nulll.

mensaje:Unable to cast object of type 'MS.Internal.NamedObject' to type 'CocoonV4.DAL.WcfServiceCocoonV4.DekoTemplate'.

at Microsoft.Practices.Prism.Commands.DelegateCommand`1.<>c__DisplayClass6.<.ctor>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.<>c__DisplayClass6.<.ctor>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& handled) 
    at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
    at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& 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& 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() 

Más EDIT:

que aísla el problema a un solo cuadro combinado declarated de la siguiente manera:

<custom:CComboBox x:Name="cmbFirstDko" 
        ItemsSource="{Binding Path=DataContext.MyFirstCollection, ElementName=myViewName}" 
        SelectedValue="{Binding anObjectID, Mode=TwoWay}" 
        SelectedValuePath="anObjectID"> 

Tenga en cuenta que la propiedad anObjectID en SelectedValue viene del DataContext ListView (este ComboBox muestra parte de un elemento de ese ListView), mientras que el anObjectID en SelectedValuePath se refiere a una propiedad que tiene cada elemento en DataContext.MyFirstCollection.

Esto me permite seleccionar un ComboBoxItem diferente para cada elemento de ListView.

Espero que mi explicación sea clara, de lo contrario dígame en los comentarios e intentaré aclarar.

de penetración: Los ComboBoxes tienen su DataContext establece en DisconnectedItem {}, este es el resultado del trabajo de los llamados SentinelObjects que intervienen cuando hay una unión entre 2 colecciones, como en mi ejemplo.

En realidad, es oficialmente un error del marco, y se ha fijado para la próxima versión, ver este MS Bug Page

¿Alguien sabe de alguna solución?

EDIT: No solía ser una respuesta ligarse a mi blog, pero mientras lo muevo personas downvoted la respuesta. Me cansé de eso, así que ahora volveré cuando esté listo.

+0

No recomendaría un colocador en las propiedades 'ObservableCollection', generalmente uso un campo' readonly' y una propiedad con solo un getter. –

+0

¿Puedes publicar cómo se implementa este RaisePropertyChanged?¿Por qué no está tomando una cuerda? – MBen

+0

@MBen: MyObsCollectionProperty es una cadena. –

Respuesta

2
  1. No hay necesidad de llamar a RaisePropertyChanged para MyObsCollection, porque ObservableCollection internal implementa INotifiyProperty Changed.
  2. Creo que se está bloqueando al asignar el valor (durante la llamada establecida), esto sucederá cuando intente asignar una colección de un tipo de colección de otro tipo. Usted tiene que crear el objeto de la MyCustomType y debe añadirse a la MyObsCollection en lugar de asignar directamente una colección de diferentes tipos de MyObsCollection

Sería muy bueno si pudiera enviar el código completo o parte del código donde u asignar la o agregue objetos a MyObsCollection

2

Tengo el mismo problema ahora, y después de eliminar el estilo estático-ressource en ItemContainerStyle y definirlo directamente debajo de ListBox, el problema desapareció.

Tenía x: Nombre la propiedad en los elementos en DataTemplate, y como los eliminé, probablemente el compilador no los creó. Así que cambié una manera para que tenga sentido.

Espero que este pequeño truco te ayude!

Cuestiones relacionadas