Created
August 31, 2021 08:33
-
-
Save javiercampos/1152da404c3004d7fbaac8e503425e4a to your computer and use it in GitHub Desktop.
Culture Switching Methods Test on Blazor Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@page "/" | |
@using System.Globalization | |
<h1>Blazor culture</h1> | |
<p> | |
@_dateTime.ToString()<br /> | |
@_decimalNumber.ToString("N4");<br /> | |
</p> | |
<h1>Specific culture</h1> | |
<p> | |
@_dateTime.ToString(_currentCulture)<br /> | |
@_decimalNumber.ToString("N4", _currentCulture);<br /> | |
</p> | |
<p> | |
<button @onclick="@SwitchCultureWithDelayAsync">Switch Culture With Delay</button> | |
<button @onclick="@SwitchCultureOnCompletedTaskAsync">Switch Culture Immediately</button> | |
</p> | |
<p> | |
<button @onclick="@SwitchCultureWithDelayNoInvokeAsync">Switch Culture With Delay (No Invoke)</button> | |
<button @onclick="@SwitchCultureOnCompletedTaskNoInvokeAsync">Switch Culture Immediately (No Invoke)</button> | |
</p> | |
@code { | |
private DateTime _dateTime = DateTime.Now; | |
private decimal _decimalNumber = 9876.54321M; | |
private readonly CultureInfo _enCulture = CultureInfo.CreateSpecificCulture("en-US"); | |
private readonly CultureInfo _esCulture = CultureInfo.CreateSpecificCulture("es-ES"); | |
private CultureInfo _currentCulture = null; | |
protected override void OnInitialized() | |
{ | |
CultureInfo.CurrentCulture = _enCulture; | |
base.OnInitialized(); | |
} | |
private void SwitchCulture() | |
{ | |
var targetCulture = ReferenceEquals(_currentCulture, _enCulture) ? _esCulture : _enCulture; | |
_currentCulture = targetCulture; | |
CultureInfo.CurrentCulture = CultureInfo.CurrentUICulture = targetCulture; | |
} | |
private async Task SwitchCultureWithDelayAsync() | |
{ | |
await InvokeAsync(async () => | |
{ | |
SwitchCulture(); | |
await Task.Delay(1000); // Don't return a completed task | |
}); | |
} | |
private async Task SwitchCultureOnCompletedTaskAsync() | |
{ | |
await InvokeAsync(() => | |
{ | |
SwitchCulture(); | |
return Task.CompletedTask; | |
}); | |
} | |
private async Task SwitchCultureWithDelayNoInvokeAsync() | |
{ | |
SwitchCulture(); | |
await Task.Delay(1000); | |
} | |
private Task SwitchCultureOnCompletedTaskNoInvokeAsync() | |
{ | |
SwitchCulture(); | |
return Task.CompletedTask; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment