【问题标题】:Loading ResourceDictionary in code behind in UWP/C++在 UWP/C++ 中的代码中加载 ResourceDictionary
【发布时间】:2017-03-30 02:16:03
【问题描述】:

我正在尝试在运行时加载存储在文件中的 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) 抛出异常:

在 wp_UWP.exe 中的 0x7464A6F2 (KernelBase.dll) 处引发异常:0x40080201:WinRT 发起错误(参数:0x8000FFFF、0x00000016、0x0D30F274)。 在 wp_UWP.exe 中的 0x7464A6F2 处引发异常:Microsoft C++ 异常:Platform::COMException ^ 在内存位置 0x0D30F714。 HRESULT:0x8000FFFF 灾难性故障 WinRT 信息:灾难性故障

wp_UWP.exe 中 0x0C9E571A (Windows.UI.Xaml.dll) 处的未处理异常:0xC000027B:发生应用程序内部异常(参数:0x00F1CA10、0x00000002)。

如何修复此代码?我不明白为什么它会抛出这样的“灾难性失败”异常。

【问题讨论】:

    标签: uwp win-universal-app c++-cx


    【解决方案1】:

    您可以在初始化主页或主页的构造函数时放置代码,它会运行良好:

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

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

    【讨论】:

    • 事实证明 OnLaunched() 和解决 App.xaml 中的问题,它有一些问题,工作。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    • 2011-08-03
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多