-
Notifications
You must be signed in to change notification settings - Fork 0
/
Localization.cs
73 lines (57 loc) · 2.23 KB
/
Localization.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace SettingsManager;
public static class Localization {
const string FallbackLocale = "en";
static Localization() {
string locale = CultureInfo.CurrentCulture.TwoLetterISOLanguageName;
Stream fallback = ResourcesUtils.GetStream($"Localization/{FallbackLocale}.json")!;
Stream current;
try {
current = ResourcesUtils.GetStream($"Localization/{locale}.json")!;
} catch (IOException) {
current = fallback;
}
Fallback = Json.Deserialize<Dictionary<string, string>>(fallback, true)!;
Translations = Json.Deserialize<Dictionary<string, string>>(current, true)!;
}
static Dictionary<string, string> Fallback { get; }
static Dictionary<string, string> Translations { get; }
public static string GetString(string path) =>
Translations.TryGetValue(path, out string value)
? value
: Fallback[path];
public static bool TryGetString(string path, out string value) =>
Translations.TryGetValue(path, out value) ||
Fallback.TryGetValue(path, out value);
}
public class LocalizationProvider {
public readonly static DependencyProperty PathProperty =
DependencyProperty.RegisterAttached(
"Path",
typeof(string),
typeof(LocalizationProvider),
new PropertyMetadata(string.Empty, OnPathChanged));
public static string GetPath(DependencyObject obj) =>
(string)obj.GetValue(PathProperty);
public static void SetPath(DependencyObject obj, string value) =>
obj.SetValue(PathProperty, value);
static void OnPathChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) {
string value = Localization.GetString((string)e.NewValue);
switch (obj) {
case TextBlock textBlock:
textBlock.Text = value;
break;
case Run run:
run.Text = value;
break;
case TabItem tabItem:
tabItem.Header = value;
break;
}
}
}