最佳答案
设计器只为 Text
属性序列化字符串。您不能直接使用设计器将 Text 属性设置为资源值。
即使您打开 Form1.Designer.cs
文件并在初始化中添加一行以将 Text
属性设置为资源值,如 Resource1.Key1
,在设计器中第一次更改后,设计器通过为 Text
属性设置该资源的字符串值来替换您的代码。
一般来说,我建议使用标准 localization Windows 窗体的机制,使用 Form
的 Localizable
和 Language
属性。
但是如果出于某种原因你想使用你的资源文件并想使用基于设计器的解决方案,那么你可以创建一个 extender component在设计时为您的控件设置资源键,然后在运行时使用它。
扩展器组件的代码在文章末尾。
用法
确保你有一个资源文件。例如属性文件夹中的 Resources.resx
。还要确保资源文件中有一些资源键/值。例如,Key1 的值为“Value1”,Key2 的值为“Value2”。然后:
- 在您的表单上放置一个
ControlTextExtender
组件。 - 使用属性网格将其
ResourceClassName
属性设置为资源文件的全名,例如 WindowsApplication1.Properties.Resources` - 选择要设置其
Text
的每个控件,并使用属性网格将 controlTextExtender1 上的ResourceKey
属性的值设置为所需的资源键。
然后运行应用程序并查看结果。
结果
这是结果的屏幕截图,如您所见,我什至通过这种方式本地化了表单的 Text
属性。
在运行时在不同文化之间切换
您可以在运行时在不同文化之间切换,无需关闭并重新打开表单,只需使用:
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fa");
this.controlTextExtender1.EndInit();
实现
下面是这个想法的基本实现:
[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;
}
}
}
关于c# - 如何在设计时将文本设置为资源文件中的控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33948734/