如何在 C# (WPF) 中获取字符串资源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13892921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a string resource in C# (WPF)?
提问by Michel Keijzers
I know how to get a resource from the string resource in XAML:
我知道如何从 XAML 中的字符串资源中获取资源:
{Binding OK, Source={StaticResource LocStrings}}
However, I want to use a localized string in C# directly, e.g. something like
但是,我想直接在 C# 中使用本地化的字符串,例如类似
someString = Resources["LocStrings"]["StringId"];
But this does not compile.
但这不能编译。
采纳答案by NoOne
You need something like this:
你需要这样的东西:
var myText = this.FindResource("LocStrings") as string;
I guess, you can change thisto wherever your resource is located.
我想,您可以更改this到您的资源所在的任何位置。
UPDATE:
更新:
Usually, this is what I use for global resources:
通常,这是我用于全局资源的内容:
var myText = Application.Current.FindResource("resourceName") as string;
回答by Robin Davies
Resource strings are accessible as static members in the auto-generated Resourcesclass, found in <Default.app.namespace>.Properties.Resources. Propertiesand Resourcesare both unfortunate namespace names that clash with properties or namespaces that you probably already have in scope when writing WPF code. So you may have to use the fully-qualified name. e.g.
资源字符串可作为自动生成的Resources类中的静态成员访问,在<Default.app.namespace>.Properties.Resources. Properties并且Resources都是不幸的命名空间名称,它们与编写 WPF 代码时可能已经在范围内的属性或命名空间发生冲突。因此,您可能必须使用完全限定名称。例如
MyProject.Properties.Resources.AppName
for the string defined in Resources.resxwith the name "AppName".
对于Resources.resx以名称“AppName”定义的字符串。
You should prefer this method of getting string resources over calling FindResource, as it provides compile-time checking of resource string names.
您应该更喜欢这种获取字符串资源的方法而不是调用FindResource,因为它提供了资源字符串名称的编译时检查。
FFS. How can this not already be given as an answer, people?
实况调查团。这怎么可能不是已经作为答案给出的,人们?
回答by Raúl Ota?o
This is not a complete answer but maybe could helps in your internationalization application, see this codeplex articlemaybe will be useful to you.
这不是一个完整的答案,但可能对您的国际化应用程序有所帮助,请参阅这篇codeplex 文章可能对您有用。

