Loading ResourceDictionary in code behind in UWP/C++

2

I'm trying to load, in runtime, ResourceDictionary that is stored in a file. In C# it looks simply as

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

but same code (in c++/cx) is not working:

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

As I get it, this code should be executed right after InitializeComponent() in App.xaml.cpp's constructor. Source is set correctly (creating URI is executed without any error).

Last line MergedDictionaries->Append(rd) throws an exception:

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).

How to fix this code? I don't understand why it throws such 'Catastrophic failure' exception.

uwp
win-universal-app
c++-cx
asked on Stack Overflow Nov 16, 2016 by Artur Siwiak

1 Answer

2

You can put the code whenever you initialize main page or in constructor of the main page and it will run fine:

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;
       }
       .. 
       ..
   }
   ..
   ..
}

Looks like it works actually everywhere except in app constructor and I have no idea why is that.

answered on Stack Overflow Nov 16, 2016 by Mehrzad Chehraz

User contributions licensed under CC BY-SA 3.0