还有另一种方法代码无限在这里 https://codinginfinity.me/post/2015-05-10/localization_of_a_wpf_app_the_simple_approach它还使用包装器来动态绑定资源文件。
这里的INotifyPropertyChanged
当区域设置更改时,事件会通知您的 ui 元素新的绑定资源文件。
您开始实现 BindingExtension:
public class LocalizationExtension : Binding
{
public LocalizationExtension(string name) : base("[" + name + "]")
{
this.Mode = BindingMode.OneWay;
this.Source = TranslationSource.Instance;
}
}
然后你需要实现a之间的连接ResourceManager
和CultureInfo
它作为单例实现以启用同步访问。它定义了绑定元素的源,并在本地化更改时触发 INotifyPropertyChanged` 事件:
public class TranslationSource : INotifyPropertyChanged
{
private static readonly TranslationSource instance = new TranslationSource();
public static TranslationSource Instance
{
get { return instance; }
}
private readonly ResourceManager resManager = Resources.Strings.Resources.ResourceManager;
private CultureInfo currentCulture = null;
public string this[string key]
{
get { return this.resManager.GetString(key, this.currentCulture); }
}
public CultureInfo CurrentCulture
{
get { return this.currentCulture; }
set
{
if (this.currentCulture != value)
{
this.currentCulture = value;
var @event = this.PropertyChanged;
if (@event != null)
{
@event.Invoke(this, new PropertyChangedEventArgs(string.Empty));
}
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
请注意,您的本地化资源文件(例如 Resource.resx、Resource.en-US.resx)位于该文件夹中<Project>/Resources/Strings/Resources/
否则你需要更新这部分代码。
现在您可以使用这个新绑定:
<Label Foreground="{StaticResource ApplicationForgroundColor}" FontSize="21"
Content="{util:Localization title}"/>
要在运行时更改区域设置,您需要设置:
public static void SetLanguage(string locale)
{
if (string.IsNullOrEmpty(locale)) locale = "en-US";
TranslationSource.Instance.CurrentCulture = new System.Globalization.CultureInfo(locale);
}