[每次我使用C#编程时,我都会将UI字符串写入WPF代码中。我认为这不是编写UI字符串的最佳实践。是否可以将它们全部保存到ResourceDictionary中?这样,它们都存储在单个文件中,而不是代码中。以后更改字符串也可能会更容易。
我如何实现这样的目标?谢谢。
无论您具有控制台应用程序还是wpf或Web,设置都是相同的。您需要做的是添加资源文件。要练习并开始使用,可以创建一个控制台应用程序,然后:
现在在main方法中添加以下代码:
// 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();
运行应用程序,输出将是:
你好卓悦
在WPF中这是相同的想法,但您将使用Console.WriteLine而不是Console.WriteLine。例如:
Title="{x:Static p:Resources.Hello}" Height="350" Width="525">