System.ArgumentException:'Value does not fall within the expected range.' 静态 class

System.ArgumentException: 'Value does not fall within the expected range.' on static class

我在我的静态设置中使用 class 我的 Winui3 应用程序中的以下方法:

private static async void CheckDocumentsCopyDialog(string targetPath)
    {
        var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForViewIndependentUse();
        ContentDialog checkDocumentsCopy = new ContentDialog()
        {
            Title = Constants.App.Name + " " + resourceLoader.GetString("MsgSetupCheckDocumentHeader"),
            Content = resourceLoader.GetString("MsgSetupCheckDocumentsCopy") + " " + targetPath + ".",
            CloseButtonText = "Ok"
        };
        await checkDocumentsCopy.ShowAsync();
    }

据我所知,它遵循 Microsoft 的 WinUI3 文档。但我得到:

也许有人知道,我能做些什么来解决它?

您必须将 ContentDialogXamlRoot 属性 设置为有效的 XamlRoot

从静态方法执行此操作的最简单方法是在 App.xaml.cs 文件中创建 m_window 字段 internal,然后访问 window 的XamlRoot 使用此字段,例如:

...
checkDocumentsCopy.XamlRoot = (App.Current as App)?.m_window.Content.XamlRoot;
await checkDocumentsCopy.ShowAsync(ContentDialogPlacement.InPlace);

App.xaml.cs:

public partial class App : Application
{
    ...
    protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
    {
        m_window = new BlankWindow2();
        m_window.Activate();
    }

    internal Window m_window;
}