【问题标题】:How can I call a string resource via a name stored in a variable?如何通过存储在变量中的名称调用字符串资源?
【发布时间】:2020-01-16 15:05:58
【问题描述】:

我想通过存储在变量中的名称调用 .resx 中的字符串类型资源。

假设我有一个包含这些列的DataGridView1

| Kiwi | Apple | Grape | 'these are the columns name

我有一个Core.resx 来存储我的资源:

| Name      | Value       | Comment | 'note how the name of the resource
| DGV_Kiwi  | Hairy Kiwi  |         | 'is "DGV_" & column.Name
| DGV_Apple | Red Apple   |         |
| DGV_Grape | White Grape |         |

加载DataGridView1的时候想把header改成资源文件的值。当然,我可以这样做:

DataGridView1.Columns(0).HeaderText = My.Resources.Core.DGV_Kiwi
DataGridView1.Columns(1).HeaderText = My.Resources.Core.DGV_Apple
DataGridView1.Columns(2).HeaderText = My.Resources.Core.DGV_Grape

但我很懒,而且我的实际项目中有很多专栏。所以我想用一个循环来做到这一点。

这是我尝试的第一件事:

For Each Col As DataGridViewColumn In Me.DataGridView1.Columns
    Col.HeaderText = My.Resources.Core.Col.Name
Next

当然,这是行不通的:

Col 不是 Core 的成员

我也试过这个:

For Each Col As DataGridViewColumn In Me.DGVComps.Columns
    Col.HeaderText = My.Resources.ResourceManager.GetObject("Core.DGV_" & Col.Name)
Next

但是My.Resources.ResourceManager.GetObject("Core.DGV_" & Col.Name) 返回Nothing

那么这件事可能吗?还是我必须按名称调用我的资源?

PS:我已经在 VB.NET 中给出了这个示例,但我也可以在 C# 中制作它。

【问题讨论】:

    标签: c# .net vb.net visual-studio resx


    【解决方案1】:

    使用

    Col.HeaderText = My.Resources.Core.ResourceManager.GetString("DGV_" & Col.Name)
    

    “核心”不是资源项名称的一部分,而是资源包本身的名称。

    使用My.Resources.ResourceManager 时,您可以访问项目的默认资源包。您可以在项目的属性对话框中的 Visual Studio 中访问它。

    【讨论】:

      猜你喜欢
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      相关资源
      最近更新 更多