在Windows 8上共享目标时出现无效的类型转换异常

15
我正在尝试使用Windows 8的“Metro Styled Apps”和MVVM Light进行实验,并且想创建共享目标-现在看起来还不错。但是,如果我在OnShareTargetActivated方法中想要向ObservableCollection添加项目,则会捕获类类型和COM对象之间的InvalidCastException。

无法将类型为“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)处
在System.Collections.ObjectModel.ObservableCollection
1.InsertItem(Int32 index, T item)处
在System.Collections.ObjectModel.Collection`1.Add(T item)处


1
希望你不介意。我已经在问题中添加了相同异常消息和堆栈跟踪的英文版本。你解决了这个问题吗? - Daniel Ballinger
4
能否让我看看您是如何创建img对象的? - SWalters
你尝试过这个吗?返回ServiceLocator.Current.GetInstance() as MainViewModel; - Jegan
你的视图模型是否在可移植类库中? - PatrickV
你的“Conversations”属性声明是什么样子的? - Avram Tudor
显示剩余4条评论
1个回答

1

不要使用显式转换,而应该使用 "as" 转换。这听起来像是服务定位器返回的实例不是 MainViewModel 对象,将该行更改为

return ServiceLocator.Current.GetInstance() as MainViewModel;

如果实例不是 MainviewModel,它的行为可能会有所不同,那么它将返回 null,这将帮助您调试为什么实例从服务定位器返回了 null

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接