How to automatically generate strongly typed classes for your Resw files

How to automatically generate strongly typed classes for your Resw files

I recently released an open-source extension for Visual Studio 2017 and Visual Studio 2019 adding many highly valuable features to .resw files, including one of the major feature from .resx missing: access to strings via strongly typed static properties.

In addition to this feature, ReswPlus also provides:

  • Auto-generation of methods to format your strings
    • Support typed and named parameters, literal strings, string references and Macros
  • Pluralization support (for 196 languages!).
    • Including: support empty states when the number of items is zero.
  • Support string variants

This extension can generate files for C# and VB.Net but also C++/CX and C++/WinRT.

How to install this extension?

You can directly download the extension here: https://marketplace.visualstudio.com/items?itemName=rudyhuyn.ReswPlus, close all instances of Visual Studio and run the .vsix file. It will install the extension on Visual Studio 2017 and Visual Studio 2019.

Generate strongly typed properties

ReswPlus can generate a class exposing all strings from your .resw files as strongly typed static properties, providing a compile-time-safe way to access those strings XAML-side or code-side.

Contrary to ResourceLoader.GetString("IdString"), the compiler will verify how your XAML and C# access your strings and won’t compile if a resource doesn’t exist, making your code more reliable and stable.

This feature will allow you to localize your applications using bindings (including native bindings) and code-behind (similar to .resx files in WPF/Silverlight applications) and will allow you to use converter, functions, etc…

The recommended way to access localization strings in your XAML is using native bindings. When native binding isn’t possible (ResourceDictionary, control template…) ReswPlus provides an alternative way to access to resources via custom MarkupExtension (verified at compilation time).

Code generated by Resw:

public class Resources {
    private static ResourceLoader _resourceLoader;
    static Resources()
    {
        _resourceLoader = ResourceLoader.GetForViewIndependentUse();
    }
    public static string WelcomeTitle => _resourceLoader.GetString("WelcomeTitle");
}

How to use it

XAML – native binding:

<TextBlock Text="{x:Bind strings:Resources.WelcomeTitle}" />

XAML – markup extension (generated by ReswPlus):

<TextBlock Text="{strings:Resources Key=WelcomeTitle}" />

Code behind:

titlebar.Title = Resources.WelcomeTitle;

Conclusion

Strongy typed class generation is only one of the many features provided by ReswPlus. You can find me information here: https://github.com/DotNetPlus/ReswPlus/wiki

And get access (and contribute) to the source code here:

https://github.com/DotNetPlus/ReswPlus/

Comments are closed.