c# - 如何在设计时将文本设置为资源文件中的控件?

标签 c# .net winforms localization windows-forms-designer

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

Set Property

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

最佳答案

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

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

一般来说,我建议使用标准 localization Windows 窗体的机制,使用 FormLocalizableLanguage 属性。

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

扩展器组件的代码在文章末尾。

用法

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

  1. 在您的表单上放置一个 ControlTextExtender 组件。
  2. 使用属性网格将其 ResourceClassName 属性设置为资源文件的全名,例如 WindowsApplication1.Properties.Resources` enter image description here
  3. 选择要设置其 Text 的每个控件,并使用属性网格将 controlTextExtender1 上的 ResourceKey 属性的值设置为所需的资源键。 enter image description here

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

结果

这是结果的屏幕截图,如您所见,我什至通过这种方式本地化了表单的 Text 属性。

enter image description here

enter image description here

在运行时在不同文化之间切换

您可以在运行时在不同文化之间切换,无需关闭并重新打开表单,只需使用:

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/

相关文章:

c# - 命名空间冲突

c# - 确定小数是否可以存储为 int32

c# - 使用 ShowDialog 显示对话框时如何控制对话框的位置?

C#:两种形式,一种是调用另一种

c# - 将多个视频文件与延迟的音频文件连接起来

c# - 如何在 Entity Framework 中创建返回 IQueryable<T> 的导航属性

c# - 没有可用的匹配绑定(bind),并且该类型在 Ninject 中不可自绑定(bind)

c# - 为什么这段代码没有编译?

c# - 在 nuget 包中显示评论

winforms - 使用 PowerShell 访问 WebView2 中的 cookie