MyNewName MyNewName - 3 days ago 4
C# Question

c# save strings in resources

Everytime I programm C# I write the UI strings for the user into my WPF code. I think that can't be the best practise. Would it be possible to save all my output strings in a

ResourceDictionary
? So I have them a stored in a single file instead of many different. And I think it's a lot easier to change strings.

How can I do this?

Answer

The setup will be the same whether you have a console application or wpf or web. What you need to do is to add resource files. To practice and get started, you can create a console application and then:

  1. Double click "properties" node of the project in the solution explorer.
  2. Click "Resources" tab.
  3. Click the link to create the resource file.
  4. In the Name column enter "Hello". This will be used in code to refer to this translation. In the value column enter "Hello". This is what the users will see.
  5. Note that a file named Resources.resx has been created under the properties node.
  6. Right click the properties node and select Add > New Item. Select Resources File and name this file exactly this: Resources.fr.resx. (fr stands for french)
  7. In the Name column enter "Hello". This will be used in code to refer to this translation. In the value column enter "Bonjour". This is what the users will see.

Now in the main method add the following code:

// Default local on my OS is En (English). If it was French it will say "Bonjour" instead.
Console.WriteLine(Resources.Hello);
// Now we change it to French so you can see how it picks the right string based on the language
// See fr in line below. This will pick up the Resources.fr.resx instead of Resources.resx
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
Console.WriteLine(Resources.Hello);
Console.ReadKey();

Run the application and the output will be:

Hello Bonjour

It would be the same idea in WPF but instead of Console.WriteLine you will use it differently. For example:

Title="{x:Static p:Resources.Hello}" Height="350" Width="525">
Comments