Inf*_*ero 4 .net c# localization windows-forms-designer winforms
我想知道Text在设计时是否存在从资源文件设置控件属性的方法:
或者这个过程只能以编程方式执行?
设计者只为字符串序列化Text属性.您不能使用designer直接将Text属性设置为资源值.
即使您打开Form1.Designer.cs文件并在初始化中添加一行以将Text属性设置为资源值,例如Resource1.Key1在设计器中首次更改之后,设计者通过为该Text属性设置该资源的字符串值来替换您的代码.
一般来说,我建议使用Windows窗体的标准本地化机制,使用Localizable和Language属性Form.
但是如果由于某种原因你想要使用你的资源文件并希望使用基于设计器的解决方案,那么你可以创建一个扩展器组件来在设计时为你的控件设置资源键,然后在运行时使用它 -时间.
扩展程序组件的代码位于帖子的末尾.
用法
确保您有一个资源文件.例如Resources.resx,在properties文件夹中.还要确保资源文件中有一些资源键/值.例如,Key1的值为"Value1",Key2的值为"Value2".然后:
ControlTextExtender在表单上放置一个组件.ResourceClassName属性设置为资源文件的全名,例如WindowsApplication1.Properties.Resources`

Text并使用属性网格将ResourceKey on controlTextExtender1属性值设置为所需的资源键.

然后运行应用程序并查看结果.
结果
这是结果的截图,如你所见,我甚Text至以这种方式本地化了表单的属性.
在运行时切换文化
您可以在运行时在不同文化之间切换,而无需关闭并重新打开表单,只需使用:
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fa");
this.controlTextExtender1.EndInit();
Run Code Online (Sandbox Code Playgroud)
履行
以下是该想法的基本实现:
[ProvideProperty("ResourceKey", typeof(Control))]
public class ControlTextExtender
: Component, System.ComponentModel.IExtenderProvider, ISupportInitialize
{
private Hashtable Controls;
public ControlTextExtender() : base() { Controls = new Hashtable(); }
[Description("Full name of resource class, like YourAppNamespace.Resource1")]
public string ResourceClassName { get; set; }
public bool CanExtend(object extendee)
{
if (extendee is Control)
return true;
return false;
}
public string GetResourceKey(Control control)
{
return Controls[control] as string;
}
public void SetResourceKey(Control control, string key)
{
if (string.IsNullOrEmpty(key))
Controls.Remove(control);
else
Controls[control] = key;
}
public void BeginInit() { }
public void EndInit()
{
if (DesignMode)
return;
var resourceManage = new ResourceManager(this.ResourceClassName,
this.GetType().Assembly);
foreach (Control control in Controls.Keys)
{
string value = resourceManage.GetString(Controls[control] as string);
control.Text = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)