如何在设计时从资源文件中将文本设置为控件?

我想知道是否存在在设计时从资源文件设置控件的Text属性的方法:

设置属性

或者这个过程只能以编程方式执行?

设计器仅序列化Text属性的字符串。 您不能使用designer直接将Text属性设置为资源值。

即使您打开Form1.Designer.cs文件并向初始化添加一行以将Text属性设置为资源值(如Resource1.Key1 ,在设计器中首次更改后,设计人员通过设置该资源的字符串值来替换您的代码for Text属性。

一般来说,我建议使用窗体的标准本地化机制,使用Form LocalizableLanguage属性。

但是如果出于某种原因你想要使用资源文件并希望使用基于设计器的解决方案,那么你可以创建一个扩展器组件来在设计时为你的控件设置资源键,然后在运行时使用它 -时间。

扩展程序组件的代码位于post的末尾。

用法

确保您有一个资源文件。 例如,properties文件夹中的Resources.resx 。 还要确保资源文件中有一些资源键/值。 例如,Key1的值为“Value1”,Key2的值为“Value2”。 然后:

  1. ControlTextExtender组件放在表单上。
  2. 使用属性网格将其ResourceClassName属性设置为资源文件的全名,例如WindowsApplication1.Properties.Resources` 在此处输入图像描述
  3. 选择要设置其Text每个控件,并使用属性网格将ResourceKey on controlTextExtender1属性ResourceKey on controlTextExtender1ResourceKey on controlTextExtender1值设置为所需的资源键。 在此处输入图像描述

然后运行应用程序并查看结果。

结果

这是结果的截图,如您所见,我甚至以这种方式对表单的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; } } }