Culture Provider & Language Switch

Comprehensive culture/localization management system for Blazor applications.

Quick Language Switch

Try switching the language to see localization in action.

1. Service Registration

Register culture services in your application's startup. Choose the appropriate method based on your Blazor hosting model.

Blazor WebAssembly (Program.cs)

csharp
// Add localization services
builder.Services.AddLocalization(options =>
    options.ResourcesPath = "Resources");

// Add FOD UI Components
builder.Services.AddFod();

// Add WASM-specific culture service
builder.Services.AddBlazorWasmCulture(options =>
{
    options.SupportedCultures = new List<string> { "en", "ro", "ru" };
    options.DefaultCulture = "en";
    options.DetectBrowserLanguage = true;
    options.StorageKey = "fod.culture";
});

// Initialize culture before running
var host = await builder.Build().UseCultureAsync();
await host.RunAsync();

Blazor Server (Program.cs)

csharp
// Add localization services
builder.Services.AddLocalization(options =>
    options.ResourcesPath = "Resources");

// Add FOD UI Components
builder.Services.AddFod();

// Add Server-specific culture service
builder.Services.AddBlazorServerCulture(options =>
{
    options.SupportedCultures = new List<string> { "en", "ro", "ru" };
    options.DefaultCulture = "en";
    options.DetectBrowserLanguage = true;
});
Available Registration Methods:
  • AddBlazorWasmCulture() - Uses localStorage for persistence, JS interop for browser detection
  • AddBlazorServerCulture() - Uses cookies for persistence, HttpContext for detection
  • AddCultureService() - Base service without platform-specific features (for testing)

2. CultureProviderOptions

Configure the culture provider behavior with these options.

No properties defined.

Current Configuration

  • Supported: en-GB, ro, ru
  • Current: en-GB

Detection Priority

  1. Stored preference (localStorage/cookie)
  2. Query parameter (?culture=xx) [Server only]
  3. Browser language (navigator.language / Accept-Language)
  4. Default culture

3. FodCultureProvider

Wrap your application with FodCultureProvider to enable culture cascading.

App.razor

razor
<FodCultureProvider>
    <Router AppAssembly="@typeof(App).Assembly">
        <Found Context="routeData">
            <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
    </Router>
</FodCultureProvider>
What FodCultureProvider does:
  • Provides CultureContext as a cascading value to all child components
  • Initializes the culture service on first render
  • Synchronizes .NET's ambient culture (CultureInfo.CurrentCulture)
  • Triggers re-renders when culture changes

4. ICultureService Interface

The main service for managing application culture state.

Interface Methods & Properties

csharp
public interface ICultureService
{
    // Properties
    CultureContext Current { get; }                    // Current culture context
    CultureInfo CurrentCulture { get; }                // Current active culture
    IReadOnlyList<CultureInfo> SupportedCultures { get; } // All supported cultures

    // Events
    event Action<CultureContext>? OnCultureChanged;   // Culture change notification

    // Methods
    Task SetCultureAsync(string cultureCode);          // Change culture
    Task InitializeAsync();                            // Initialize (detect/load)
    CultureInfo GetCultureByCode(string? code);        // Lookup culture by code
}

Usage Example

csharp
@inject ICultureService CultureService

// Get current culture info
var current = CultureService.CurrentCulture;
var supported = CultureService.SupportedCultures;

// Change culture programmatically
await CultureService.SetCultureAsync("ro");

// Subscribe to culture changes
CultureService.OnCultureChanged += context =>
{
    Console.WriteLine($"Culture changed to: {context.LanguageCode}");
};

5. CultureContext Record

The culture context cascaded to all child components.

Properties

No properties defined.

Current Values

CurrentCulture en-GB
LanguageCode en
NativeDisplayName English (United Kingdom)
DisplayName English (United Kingdom)

Accessing via Cascading Parameter

csharp
[CascadingParameter]
protected CultureContext? CultureContext { get; set; }

// Use in component
var langCode = CultureContext?.LanguageCode;
var nativeName = CultureContext?.NativeDisplayName;

6. CultureAwareComponentBase

Base class for components that need automatic re-rendering on culture changes.

Creating a Culture-Aware Component

csharp
public class MyCultureAwareComponent : CultureAwareComponentBase
{
    // Automatically re-renders when culture changes!

    // Override for custom logic on culture change
    protected override void OnCultureChanged(CultureContext context)
    {
        // Custom logic here
        Console.WriteLine($"Culture changed to: {context.LanguageCode}");
    }
}
Benefits of CultureAwareComponentBase:
  • Automatic subscription to OnCultureChanged event
  • Automatic unsubscription on disposal (no memory leaks)
  • Syncs ambient culture before notifying derived classes
  • Virtual OnCultureChanged method for custom logic

7. Localization with IStringLocalizer

Use .NET's built-in localization with resource files.

Resource File Structure

text
Resources/
  Pages.LanguageSwitchDemo.resx       (default/fallback)
  Pages.LanguageSwitchDemo.en.resx    (English)
  Pages.LanguageSwitchDemo.ro.resx    (Romanian)
  Pages.LanguageSwitchDemo.ru.resx    (Russian)

Usage in Razor Component

razor
@using Microsoft.Extensions.Localization
@inject IStringLocalizer<LanguageSwitchDemo> L

<h1>@L["Welcome"]</h1>
<p>@L["Description"]</p>

<!-- With parameters -->
<p>@L["Greeting", userName]</p>

<!-- For attributes -->
<FodTextField Label="@L["NameLabel"].Value" />

Live Localization Demo

Greeting: Greeting

Welcome: Welcome

Description: Description

8. Culture-Dependent Formatting

Date, time, number, and currency formatting automatically adapts to the current culture.

CurrentDate

Wednesday 20 May 2026

DateTime.Now.ToString("D", culture)

CurrentTime

11:27:06

DateTime.Now.ToString("T", culture)

Number

1,234,567.89

number.ToString("N2", culture)

Currency

£1,234.56

amount.ToString("C", culture)

Short Date

20/05/2026

DateTime.Now.ToString("d", culture)

Percent

85.7%

value.ToString("P1", culture)

9. FodLanguageSwitch

Ready-to-use component for language selection with two display modes.

Mode 1: Inline

Simple horizontal list of language codes. Best for headers or navigation bars.

Disabled

Default

razor
<FodLanguageSwitch Mode="LanguageSwitchMode.Inline" />

Mode 2: Dropdown

Dropdown button with globe icon and full language names. Best for compact spaces.

razor
<FodLanguageSwitch Mode="LanguageSwitchMode.Dropdown" />

Component Parameters

No properties defined.

Usage with Callback

razor
<FodLanguageSwitch
    Mode="LanguageSwitchMode.Dropdown"
    OnLanguageChanged="HandleChanged" />

@code {
    private void HandleChanged(CultureInfo culture)
    {
        Console.WriteLine($"Changed to: {culture.Name}");
    }
}

10. Supported Languages

List of all configured languages with their native names.

EN English (United Kingdom) English (United Kingdom)Active
RO română Romanian
RU русский Russian

11. Localized Form Example

Form fields and buttons with localized labels that update when language changes.

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please reload the page.