繁体   English   中英

共享数据并添加到ObservableCollection时出现InvalidCastException

[英]InvalidCastException when sharing data and adding to ObservableCollection

我正在尝试使用共享合同将数据从Edge发送到我的UWP应用程序。 它就像一个魅力,除非我尝试将以这种方式接收的数据添加到ObservableCollection<T>我得到此异常:

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

代码如下:

App.xaml.cs:

protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
  {
     if (this.SharingService != null)
        await this.SharingService.OnShareTargetActivated(args);
  }

SharingService.cs:

public delegate void UriAddedEventHandler(object sender, UriAddedEventArgs args);
public event UriAddedEventHandler UriAdded;

public async Task OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
   var shareOperation = args.ShareOperation;

   if (shareOperation.Data.Contains(StandardDataFormats.WebLink))
   {
      var uri = await shareOperation.Data.GetWebLinkAsync();

      this.UriAdded?
         .Invoke(this, new UriAddedEventArgs { Uri = uri });
   }
}

ViewModel.cs:

public ViewModel(ISharingService sharingService)
{
   sharingService.UriAdded += OnUriAdded;
}

public ObservableCollection<Uri> collection = new ObservableCollection<Uri>();

private async void OnUriAdded(object sender, UriAddedEventArgs args)
{
   this.collection.Add(args.Uri));
}

当然,该集合绑定到页面上的元素。

当事件触发时,我似乎在一个不同的线程上(毫不奇怪),但将操作包装在一个

await Window.Current.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, ...)

没有改变任何东西,我仍然得到那个例外。 有谁知道这里发生了什么?

编辑:

为了它的价值,我尝试使用.NET本机工具链进行编译并发现此警告:

警告:DEP0810:此应用程序引用了SDK中的Microsoft.NET.Native.Runtime.1.1,版本1.1.23231.0,但您在目标计算机上安装了更高版本的Microsoft.NET.Native.Runtime.1.1,1.1 .23406.0。 如果继续运行此应用程序,它将针对当前安装的版本Microsoft.NET.Native.Runtime.1.1,版本1.1.23406.0运行。 请考虑更新SDK以匹配已安装的Microsoft.NET.Native.Runtime.1.1版本。

所以,是的,我开始怀疑这里有一些版本冲突。 我安装了最新的Windows 10 SDK( 10.0.26624.0 ),所以我不确定如何按照上面的警告更新我的SDK。

每个窗口(您的主应用程序和共享窗口)都有唯一的调度程序。

您无法直接将UI或调度程序从一个窗口引用到另一个窗口。

可以调用后台线程,然后使用其他窗口的调度程序。

我的建议是摆脱调度程序的所有全局getter并使用页面的调度程序(this.Dispatcher)。 最佳做法是使用您要显示内容的相应控件或页面的调度程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM