diff --git a/src/Ursa.Themes.Semi/Index.axaml.cs b/src/Ursa.Themes.Semi/Index.axaml.cs index a478b5aa..efa20383 100644 --- a/src/Ursa.Themes.Semi/Index.axaml.cs +++ b/src/Ursa.Themes.Semi/Index.axaml.cs @@ -19,7 +19,7 @@ public class SemiTheme : Styles }; private static readonly ResourceDictionary _defaultResource = new zh_cn(); - + private CultureInfo? _locale; public SemiTheme(IServiceProvider? provider = null) @@ -39,10 +39,16 @@ public CultureInfo? Locale { try { - _locale = value; - var resource = TryGetLocaleResource(value); - if (resource is null) return; - foreach (var kv in resource) Resources.Add(kv); + if (TryGetLocaleResource(value, out var resource) && resource is not null) + { + _locale = value; + foreach (var kv in resource) Resources[kv.Key] = kv.Value; + } + else + { + _locale = new CultureInfo("zh-CN"); + foreach (var kv in _defaultResource) Resources[kv.Key] = kv.Value; + } } catch { @@ -51,12 +57,28 @@ public CultureInfo? Locale } } - private static ResourceDictionary? TryGetLocaleResource(CultureInfo? locale) + private static bool TryGetLocaleResource(CultureInfo? locale, out ResourceDictionary? resourceDictionary) { - if (Equals(locale, CultureInfo.InvariantCulture)) return _defaultResource; - if (locale is null) return _localeToResource[new CultureInfo("zh-CN")]; - if (_localeToResource.TryGetValue(locale, out var resource)) return resource; - return _localeToResource[new CultureInfo("zh-CN")]; + if (Equals(locale, CultureInfo.InvariantCulture)) + { + resourceDictionary = _defaultResource; + return true; + } + + if (locale is null) + { + resourceDictionary = _defaultResource; + return false; + } + + if (_localeToResource.TryGetValue(locale, out var resource)) + { + resourceDictionary = resource; + return true; + } + + resourceDictionary = _defaultResource; + return false; } public static void OverrideLocaleResources(Application application, CultureInfo? culture) diff --git a/tests/HeadlessTest.Ursa/Semi/LocalizationTest.cs b/tests/HeadlessTest.Ursa/Semi/LocalizationTest.cs new file mode 100644 index 00000000..fd6c0df4 --- /dev/null +++ b/tests/HeadlessTest.Ursa/Semi/LocalizationTest.cs @@ -0,0 +1,101 @@ +using System.Globalization; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Headless.XUnit; +using Avalonia.Threading; +using Avalonia.VisualTree; +using Semi.Avalonia.Locale; +using Ursa.Controls; +using Ursa.Themes.Semi; + +namespace HeadlessTest.Ursa.Semi; + +public class LocalizationTest +{ + [AvaloniaFact] + public void Default_Locale_Is_Chinese() + { + var window = new UrsaWindow(); + window.Show(); + MessageBox.ShowOverlayAsync("Hello World", button: MessageBoxButton.YesNo, toplevelHashCode: window.GetHashCode()); + Task.Delay(100).Wait(); + Dispatcher.UIThread.RunJobs(); + var dialog = window.GetVisualDescendants().OfType().SingleOrDefault(); + var yesButton = dialog?.GetVisualDescendants().OfType