在 UWP/C++ 的代码后面加载 ResourceDictionary

Loading ResourceDictionary in code behind in UWP/C++

我正在尝试在运行时加载存储在文件中的 ResourceDictionary。在 C# 中,它看起来很简单

ResourceDictionary resourceDictionary = new ResourceDictionary();
resourceDictionary.Source = new Uri("ms-appx:///!UWP/Styles/UWPDictionary.xaml", UriKind.Relative);
Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);

但相同的代码(在 c++/cx 中)不起作用:

auto rd = ref new ResourceDictionary();
rd->Source = ref new Uri("ms-appx:///!UWP/Styles/UWPDictionary.xaml");
Application::Current->Resources->MergedDictionaries->Append(rd);

据我所知,这段代码应该在 App.xaml.cpp 的构造函数中的 InitializeComponent() 之后立即执行。源设置正确(创建 URI 执行时没有任何错误)。

最后一行MergedDictionaries->Append(rd)抛出异常:

Exception thrown at 0x7464A6F2 (KernelBase.dll) in wp_UWP.exe: 0x40080201: WinRT originate error (parameters: 0x8000FFFF, 0x00000016, 0x0D30F274). Exception thrown at 0x7464A6F2 in wp_UWP.exe: Microsoft C++ exception: Platform::COMException ^ at memory location 0x0D30F714. HRESULT:0x8000FFFF Catastrophic failure WinRT information: Catastrophic failure

Unhandled exception at 0x0C9E571A (Windows.UI.Xaml.dll) in wp_UWP.exe: 0xC000027B: An application-internal exception has occurred (parameters: 0x00F1CA10, 0x00000002).

如何修复此代码?我不明白为什么会抛出这样的 'Catastrophic failure' 异常。

您可以在初始化主页时或在主页的构造函数中放置代码,它 运行 没问题:

void App::OnLaunched
(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e)
{  
    auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr)
    {
       // Load the dictionary if not already loaded
       if (!resourcesLoaded) {
          auto rd = ref new ResourceDictionary();
          rd->Source = ref new Uri("ms-appx:///Dictionary.xaml");
          Application::Current->Resources->MergedDictionaries->Append(rd);
          resourcesLoaded = true;
       }
       .. 
       ..
   }
   ..
   ..
}

看起来它实际上在任何地方都有效,除了在应用程序构造函数中,我不知道为什么会这样。