【问题标题】:Read key, value and comment from resources in a .resx file从 .resx 文件中的资源中读取键、值和注释
【发布时间】:2016-01-08 10:50:15
【问题描述】:

我有一个 .resx 文件包含字符串名称值对。现在我想使用 C#(Windows 窗体)务实地将名称和值对放入 List 中。我怎样才能做到这一点。但这是列表中价值成就的一个转折,我有一个“组合框”和两个文本框。在运行时,所有的键都应该添加到组合框中,并且其他两个测试框会自动填充值和注释。请帮助我完成这项任务。 提前致谢...

【问题讨论】:

  • “在列表中我有一个“组合框”和两个文本框是什么意思?请澄清您的问题,并在可能的情况下发布一些代码。 :)
  • 嗨 @LucaMus 我想将所有键附加到组合框中,并与 resx 文件中存在的每个键对应的值和注释。我希望当我通过组合框选择一个键时,该键的值和注释会自动出现在带有值的 textBox1 和带有 commnet 的 textbox2 中

标签: c# winforms resx


【解决方案1】:

看看ResXResourceReader,这可以轻松完成您想做的事情。

例如,您可以执行以下操作:

    private void Form1_Load(object sender, EventArgs e)
    {
        //ComboBox will use "Name" property of the items you add
        comboBox1.DisplayMember = "Name";
        //Create the reader for your resx file
        ResXResourceReader reader = new ResXResourceReader("C:\\your\\file.resx");
        //Set property to use ResXDataNodes in object ([see MSDN][2])
        reader.UseResXDataNodes = true;
        IDictionaryEnumerator enumerator = reader.GetEnumerator();

        while (enumerator.MoveNext())
        {   //Fill the combobox with all key/value pairs
            comboBox1.Items.Add(enumerator.Value);
        }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (comboBox1.SelectedIndex == -1)
            return;

        //Assembly is used to read resource value
        Assembly currentAssembly = Assembly.GetExecutingAssembly();
        //Current resource selected in ComboBox
        ResXDataNode node = (ResXDataNode)comboBox1.SelectedItem;

        //textBox2 contains the resource comment
        textBox2.Text = node.Comment;
        //Reading resource value, you can probably find a smarter way to achieve this, but I don't know it
        object value = node.GetValue(new AssemblyName[] { currentAssembly.GetName() });
        if (value.GetType() != typeof(String))
        {   //Resource isn't of string type
            textBox1.Text = "";
            return;
        }

        //Writing string value in textBox1
        textBox1.Text = (String)value;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    相关资源
    最近更新 更多