Skip to content

Instantly share code, notes, and snippets.

@BrandonStudio
Last active December 26, 2022 12:45
Show Gist options
  • Save BrandonStudio/33a6e148147264f90eb7cdbf79786cce to your computer and use it in GitHub Desktop.
Save BrandonStudio/33a6e148147264f90eb7cdbf79786cce to your computer and use it in GitHub Desktop.
.NET MAUI Globalized String Markup Extension.
/// <summary>
/// Xaml extension providing globalized strings.
/// </summary>
/// <remarks>
/// Providing key itself if specified string is not found,
/// </remarks>
public class StringsExtension : IMarkupExtension<string>
{
/// <summary>
/// Key of globalized strings.
/// </summary>
public string Key { get; set; }
/// <summary>
/// Culture in which strings is shown.
/// </summary>
/// <remarks>
/// Default is <see cref="CultureInfo.CurrentUICulture" />.
/// </remarks>
[TypeConverter(typeof(CultureInfoConverter))]
public CultureInfo Culture { get; set; } = CultureInfo.CurrentUICulture;
private static readonly ResourceManager s_resourceManager = new(
$"{nameof(ns)}.Resources.Strings", typeof(StringsExtension).Assembly); // Replace "ns" with your own project/namespace name
public string ProvideValue(IServiceProvider serviceProvider) => s_resourceManager.GetString(Key, Culture) ?? Key;
object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) => ProvideValue(serviceProvider);
}
@BrandonStudio
Copy link
Author

See Resources in text files.
Assuming files are organized like

YourMauiProject\
    Platforms\
    Properties\
    Resources\
        AppIcon\
        ...
        Strings.restext
        Strings.ru.restext
        Strings.zh-Hans.restext
        ...
    App.config
    ...
    YourMauiProject.csproj

where resource text files are named "Strings" and stored in Resources folder just as line 24.
Make sure your resource text files ends with ".restext" and you add them to csproj:

<Project Sdk="Microsoft.NET.Sdk">
    ...
    <ItemGroup>
        <EmbeddedResource Include="Resources\*.restext" />
    </ItemGroup>
    ...
</Project>

See my example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment