参考文章:https://blog.csdn.net/u010839204/article/details/103932044
本文在该文章的基础上进行了 “改进”
这个是基类库,基本处理均在基类库里面完成。须注意 StringResources.resx名字和StringResourcesExtension前部分名字须保持一致。
类 StringResourcesExtension:
namespace Fpi.HandyControl.Language { [MarkupExtensionReturnType(typeof(BindingExpression))] public class StringResourcesExtension : MarkupExtension { /// <summary> /// 资源的名称,与资源文件StringResource.resx对应 /// </summary> [ConstructorArgument("key")] public string Key { get; set; } /// <summary> /// 获取资源内容 /// </summary> public string Value { get => StringResourcesManager.GetString(this.GetType(), Key); } public StringResourcesExtension(string key) : this() { Key = key; } public StringResourcesExtension() { } /// <summary> /// 重写函数 /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> public override object ProvideValue(IServiceProvider serviceProvider) { Binding binding = new Binding("Value") { Source = this, Mode = BindingMode.OneWay }; return binding.ProvideValue(serviceProvider); } } }
类 StringResourcesManager:
namespace Fpi.HandyControl.Language { public class StringResourcesManager { /// <summary> /// 获取字符串 /// </summary> /// <param name="name"></param> /// <returns></returns> public static string GetString(Type type, string name) { ResourceManager resource = null; var assembly = type.Assembly; if (resourcedic.ContainsKey(assembly)) { resource = resourcedic[assembly]; } else { string ex = "Extension"; resource = new ResourceManager(type.FullName.Substring(0, type.FullName.Length - ex.Length), assembly); resourcedic.Add(assembly, resource); } return resource.GetString(name, CultureInfo); } private static Dictionary<Assembly, ResourceManager> resourcedic = new Dictionary<Assembly, ResourceManager>(); }
基类库完成后,开始写应用库
同样StringResources.resx名字和StringResourcesExtension前部分名字要一致
此时多语言文件对应的文件夹下建一个StringResourcesExtension类即可
namespace HandyControlTest.Language { public class StringResourcesExtension : Fpi.HandyControl.Language.StringResourcesExtension { public StringResourcesExtension() : base() { } public StringResourcesExtension(string key) : base(key) { } } }
类里面不需要写什么代码就继承一下,构造函数加一下,就可以了。目前暂时没想到如何把这一个类省略掉的方法。
xaml中调用:
xmlns:lang="clr-namespace:HandyControlTest.Language" xmlns:lang1="clr-namespace:Fpi.HandyControl.Language;assembly=Fpi.HandyControl"
<Button Name="btntest2" Content="{lang:StringResources Test}" Width="100" Height="35" Grid.Row="2" Grid.Column="1"></Button> <Button Name="btntest1" Content="{lang1:StringResources Test}" Width="100" Height="35" Grid.Row="4" Grid.Column="1"></Button>
试了基类库和应用库两个都可以直接用,后续每增加一个应用类库,只要建个文件夹,创建一个类继承一下就可以了,无需增加额外代码。
标签:resx,assembly,StringResourcesExtension,Language,Xaml,WPF,public,string From: https://www.cnblogs.com/mqxs/p/18017436