1

我正在尝试通过共享合同在 Windows 8 商店应用程序中接收共享文本。我可以接收文本,但如果文本进入可观察集合,我会收到一个 com 异常。如何接收共享文本并将其正确传递给可移植类库中的视图模型?

可移植类库:

ViewModel.cs:

public class ViewModel
{
    public ObservableCollection<string> Strings { get; private set; }

    public ViewModel()
    {
        Strings = new ObservableCollection<string>
        {
            "one",
            "two",
            "three"
        };
    }
}

定位器.cs:

public class Locator
{
    private static ViewModel vm;
    public static ViewModel VM
    {
        get
        {
            if (vm == null)
            {
                vm = new ViewModel();
            }
            return vm;
        }
    }
}

商店应用项目:

主页.xaml

<Page...>
    <Page.Resources>
        <vm:Locator x:Key="Locator"/>
    </Page.Resources>

    <Grid ... DataContext="{Binding VM, Source={StaticResource Locator}}">
        <ListBox ItemsSource="{Binding Strings}" .../>
    </Grid>
</Page>

App.xaml.cs(缩写):

protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    base.OnShareTargetActivated(args);
    if (args.ShareOperation.Data.AvailableFormats.Contains("Text"))
    {
        var text = await args.ShareOperation.Data.GetTextAsync();
        Locator.VM.Strings.Add(text);
    }
}

上面的最后一行( Locator.VM.Strings.Add(text) )引发以下异常:

mscorlib.dll 中出现“System.InvalidCastException”类型的未处理异常

附加信息:无法将类型为“System.Collections.Specialized.NotifyCollectionChangedEventHandler”的 COM 对象转换为类类型“System.Collections.Specialized.NotifyCollectionChangedEventHandler”。表示 COM 组件的类型的实例不能转换为不表示 COM 组件的类型;但是,只要底层 COM 组件支持对接口的 IID 的 QueryInterface 调用,它们就可以转换为接口。

4

0 回答 0