wpf 使用来自应用程序其他类的“FindResource”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26303094/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:36:09  来源:igfitidea点击:

Use "FindResource" from other classes of the application

c#xmlwpfstaticresources

提问by Piero Alberto

I have to use the method FindResource("key"). In my MainWindow class, it works.

我必须使用 FindResource("key") 方法。在我的 MainWindow 类中,它有效。

I've to use it in another class, but I can't refer to it with a new instance of the MainWindow class, because this gives me some problem (not relevant now).

我必须在另一个类中使用它,但我不能用 MainWindow 类的新实例引用它,因为这给我带来了一些问题(现在不相关)。

So, I have declared a static method in my MainWindow class, but, thus I can't use "this" in a static method, I have written:

所以,我在 MainWindow 类中声明了一个静态方法,但是,因此我不能在静态方法中使用“this”,我写了:

public static string getFromDict(string key){
    View.MainWindow v = new View.MainWindow();
    return v.getResource(key);
}

private string getResource(string key) {
    return this.FindResource(key).ToString();
}

This is still giving me problems, because, as you can see, I create a new instance of MainWindow also here.

这仍然给我带来问题,因为如您所见,我也在此处创建了 MainWindow 的新实例。

So, from another class, how can I use the findResource method? (the resource I want to read are some dicts in xml, included in the project: I already read them correctly in other code).

那么,在另一个类中,我如何使用 findResource 方法?(我想阅读的资源是xml中的一些dicts,包含在项目中:我已经在其他代码中正确阅读了它们)。

回答by Won Hyoung Lee

You don't need to call MainWindow's FindResource if there is resource dictionary.
You can call FindResource as follow,

如果有资源字典,则不需要调用 MainWindow 的 FindResource。
您可以按如下方式调用 FindResource,

using System.Windows;

Application.Current.FindResource("YOUR-RESOURCE-KEY");