从应用程序的其他类使用“FindResource”

时间:2023-01-21 20:31:39

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中的一些词条,包含在项目中:我已经在其他代码中正确阅读了它们)。

1 个解决方案

#1


9  

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");

#1


9  

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");