无法将类型为“System.Collections.Specialized.NotifyCollectionChangedEventHandler”的COM对象转换为类类型“System.Collections.Specialized.NotifyCollectionChangedEventHandler”。代表COM组件的类型的实例不能转换为不代表COM组件的其他类型。但是,如果基础COM组件支持对接口IID的QueryInterface调用,则可以将其转换为接口。
英文原文:
无法将类型为“System.Collections.Specialized.NotifyCollectionChangedEventHandler”的COM对象转换为类类型“System.Collections.Specialized.NotifyCollectionChangedEventHandler”。表示COM组件的类型的实例不能转换为不表示COM组件的类型;但是,只要基础COM组件支持IID接口的QueryInterface调用,它们就可以转换为接口。现在我有点困惑,不知道如何正确处理这种行为。
MainViewModel main1 = new ViewModelLocator().Main;
MainViewModel main2 = new MainViewModel();
var conversation = new ConversationViewModel();
conversation.Messages.Add(new MessageViewModel { Image = img, Text = "Share" });
main1.Conversations.Add(conversation); // error InvalidCastException
main2.Conversations.Add(conversation); // no error
其中img
是新创建的BitmapImage
ViewModelLocator
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<UserViewModel>();
SimpleIoc.Default.Register<UriViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
//...
}
堆栈跟踪:
在System.StubHelpers.StubHelpers.GetCOMIPFromRCW_WinRTDelegate(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget)处
在System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)处
在System.Collections.ObjectModel.ObservableCollection1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)处
1.InsertItem(Int32 index, T item)处
在System.Collections.ObjectModel.ObservableCollection
在System.Collections.ObjectModel.Collection`1.Add(T item)处