无法在 Microsoft 商店中为 Wpf Core Desktop Bridge 实施应用内购买

问题描述

我的应用程序使用 .NET 5 和 Desktop Bridge。因为我使用的是 Desktop Bridge,所以我像许多在线指南一样实现了 IInitializeWithWindow 接口。

[ComImport]
[Guid("3E68D4BD-7135-4D10-8018-9FB6D9F33FA1")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnkNown)]
public interface IInitializeWithWindow
{
     void Initialize(IntPtr hwnd);
}

在这里一个方法可以在 Microsoft 商店中执行应用内购买:

private StoreContext storeContext = StoreContext.GetDefault();

IInitializeWithWindow initwindow = (IInitializeWithWindow)(object)storeContext;
var ptr = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;

//Call the IInitializeWithWindow.Initialize method,and pass the handle of the window 
//to be the owner for any modal dialogs that are shown by StoreContext methods.
initwindow.Initialize(ptr);

result = await storeContext.RequestPurchaseAsync(storeID);

问题是,当我运行应用程序时,我收到错误“无法将类型为 'Windows.Services.Store.StoreContext' 的对象转换为类型为 'IInitializeWithWindow'”。

说我使用的是 net5.0-windows10.0.18362.0 TFM(目标框架)可能很重要。 我认为问题在于我使用的是 .NET 5,它可能不受支持

解决方法

试试这个适用于 .NET 5 项目的解决方案。

using Windows.Services.Store;
using WinRT;

StoreContext storeContext = StoreContext.GetDefault();
private async Task Buy()
{
     var initWindow = storeContext.As<IInitializeWithWindow>();
     initWindow.Initialize(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);
     var productResult = await storeContext.RequestPurchaseAsync(storeID);
}