Search code examples
c++windows-runtimec++-winrtwinui-3

WinUI 3 C++/WinRT loading string resources


I have a basic WinUI3 C++/WinRT app, containing a resw file with a simple entry named "APPNAME". I wish to put that string in the title of my Xaml form.

My MainWindow.xaml.cpp has this snippet of code in it.

MainWindow::MainWindow()
    {
        InitializeComponent();

        auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForViewIndependentUse()};
        hstring title = resourceLoader.GetString(L"APPNAME");
        this->Title(title);

    } 

The issue seems to be that "Windows::ApplicationModel::Resources" isn't correct. So the question becomes how to access that resw string entry in C++/WinRT?

Many thanks,

Jason


Solution

  • With WinUI 3, most namespaces usually start with Microsoft, instead of Windows (which was more for UWP).

    It's actually difficult to get to the WinUI3-only documentation, here is some: Manage resources with MRT Core

    The WinUI 3 resource entry point is now the Microsoft.Windows.ApplicationModel.Resources.ResourceManager class.

    So, for a "MyString" string resource in a "Resources.resw" file

    enter image description here

    You can now do this:

    Microsoft::Windows::ApplicationModel::Resources::ResourceManager rm{};
    auto str = rm.MainResourceMap().GetValue(L"Resources/MyString").ValueAsString();
    

    Note that you need to #include <winrt/Microsoft.Windows.ApplicationModel.Resources.h> after Xaml includes to compile.