2015-11-06 17 views
3

我試圖從邊緣發送數據到我的UWP應用程序使用共享合同。它的工作原理就像一個魅力,只是當我嘗試以這種方式接收到的數據添加到ObservableCollection<T>我得到這個異常:InvalidCastException當共享數據並添加到ObservableCollection

InvalidCastException的: 無法投類型的COM對象System.Collections.Specialized.NotifyCollectionChangedEventHandler '類類型'System.Collections.Specialized.NotifyCollectionChangedEventHandler'。表示COM組件的類型實例不能轉換爲不代表COM組件的類型;然而,他們可以投,只要基礎COM組件支持的QueryInterface調用該接口的IID,界面*

代碼如下:

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:這個程序引用Microsoft.NET。在您的SDK中找到Native.Runtime.1.1版本1.1.23231.0,但在目標機器1.1.23406.0上安裝了更高版本的Microsoft.NET.Native.Runtime.1.1。如果您繼續運行此應用程序,它將針對當前安裝的版本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。

+1

[此鏈接](https://social.msdn.microsoft.com/Forums/windows/en-US/86201dcf-7de2-40b8-bd71-3f6527ca105c/unable-to-cast-object-of-type- x-to-type-x?forum = winformsdesigner)可能有幫助 –

+0

好的,所以Edge似乎使用了不同版本的問題DLL比我的應用程序。問題是,我該如何解決這個問題? –

+1

我向MSFT證實您的.net本機警告是預期的。這裏沒什麼可擔心的。 – Quincy

回答

5

每個窗口(您的主應用程序和您的共享窗口)都有獨特的調度程序。

您無法直接將UI或調度程序從一個窗口引用到另一個窗口。

可以調用後臺線程,然後使用其他窗口的調度程序。

我的建議是擺脫調度員的所有全局getter並使用頁面調度器(this.Dispatcher)。最佳做法是使用您要顯示內容的相應控件或頁面的調度程序。

+0

感謝您確認我一直懷疑一段時間。我將通過將URI保存到一個文件(無論如何我需要這樣做),然後從應用程序線程中觀看文件來解決此問題;當文件更新時,我將讀取內容並從那裏觸發UI更新。 –