.NET MAUI中Windows.Services.Store的RequestPurchaseAsync失效求助
解决.NET MAUI中Windows.Services.Store RequestPurchaseAsync无响应的问题
问题分析
在.NET MAUI的Windows平台调用RequestPurchaseAsync()时不弹出商店登录界面、一直处于等待状态,但其他商店相关API正常运行,且同一段代码在UWP中可正常执行。核心原因是MAUI的WinUI3窗口上下文与UWP不同,StoreContext需要手动关联当前窗口句柄,否则无法正确唤起模态对话框。另外你的代码中存在变量引用错误,也可能导致逻辑异常。
修复步骤
1. 修正代码中的变量错误
你的PurchaseAsync方法里,判断productResult.ExtendedError但实际定义的变量是myApp,这会引发逻辑错误,先修正:
public static async void PurchaseAsync() { StoreContext appinfo = StoreContext.GetDefault(); StoreProductResult myApp = await appinfo.GetStoreProductForCurrentAppAsync(); // 修正变量引用:productResult → myApp if (myApp.ExtendedError != null) { return; } StoreAppLicense license = await appinfo.GetAppLicenseAsync(); if (license.IsTrial) { StorePurchaseResult result = await myApp.Product.RequestPurchaseAsync(); if (result.ExtendedError != null) { return; } } }
2. 手动关联StoreContext到MAUI窗口
MAUI的WinUI3架构下,StoreContext无法自动识别当前窗口,需要显式绑定窗口句柄。添加以下逻辑:
using WinRT.Interop; public static async void PurchaseAsync() { StoreContext appinfo = StoreContext.GetDefault(); // 获取当前MAUI WinUI窗口的句柄并关联到StoreContext var currentWindow = MauiWinUIWindow.Current; if (currentWindow != null) { IntPtr hwnd = WindowNative.GetWindowHandle(currentWindow); InitializeWithWindow.Initialize(appinfo, hwnd); } StoreProductResult myApp = await appinfo.GetStoreProductForCurrentAppAsync(); if (myApp.ExtendedError != null) { return; } StoreAppLicense license = await appinfo.GetAppLicenseAsync(); if (license.IsTrial) { StorePurchaseResult result = await myApp.Product.RequestPurchaseAsync(); if (result.ExtendedError != null) { return; } } }
3. 替换async void为async Task(推荐)
async void会导致异常无法被捕获,建议修改方法签名:
public static async Task PurchaseAsync() { // 内部逻辑与上述一致 }
原理说明
UWP应用中StoreContext会自动关联当前窗口,但MAUI的WinUI3窗口管理机制不同,必须通过InitializeWithWindow显式将StoreContext绑定到当前窗口句柄,才能让商店的模态对话框正确附着到MAUI窗口,解决无响应问题。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

