开发者

WPF Globalization (Perhaps Not)

I am trying to build an prototype with labels, buttons, and so on. However, I do want the text in the labels or buttons to be customized through an external files, perhaps a text file or excel file. How can I achieve this?

Currently, I am trying on using a CSV file as in the following format.

Dashboard Title, Dashboard Box 1 Column Name, Box 1 Button 1, Next

And in my codes, I read them into the text field as follows.

string[] lines = File.ReadAllLines("Dashboard.csv");
for (int i = 0; i < lines.Length; i++)
{
    string currentLine = lines[i];
    string[] lineValues = currentLine.Split(',');
    switch (i)
    {
        case 0: dashboardTitle.Content = lineValues[1];
        case 1: box1ColName.Content = lineValues[1];
        case 2: button1.Content = lineValues[1];
    }
}

My worry now is that as the number of fields (elements) grow. I would have to extends the switch part perhaps up to case 100? How can I specify them perhaps in the CSV file to fill in the lable, buttons accord开发者_开发百科ingly?


Try using a name = value format in your file.

e.g. 

button1 = "My name is button1"
label2 = "This is a label"

Load these values into a dictionary

Dictionary<string, string> d = new Dictionary<string, string>();    
d.Add("button1", "My name is button1");    
d.Add("label2", "This is a label");    

You can then do the following algorithm. Loop through all the components on your form. If the component name matches the dictionary key, set the appropriate value. e.g.:

  Control.ControlCollection coll = this.Controls;
  foreach(Control c in coll) 
  {
    if(c != null)
    {
       if (d.ContainsKey(c.Name))
       {
         c.Text = d[c.Name];
       }
    }
  }

Another way of finding controls is using the:
Control.ControlCollection.Find method. Its much easier to search for controls by name.

Note however, that not all controls will have a ".Text" property, so you have to check for the type of control. However, I would also strongly suggest you learn how to use resource files. Its a commonly accepted way of handling resource strings.


Scott Hanselman has just recently written a blog post that might fit to you. It was written with ASP.NET as an example, but it is explicitely not limited to it:

Globalization, Internationalization and Localization in ASP.NET MVC 3, JavaScript and jQuery - Part 1

This starts a nine-page long article about the topic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜