【问题标题】:Use "FindResource" from other classes of the application使用应用程序其他类的“FindResource”
【发布时间】:2014-10-10 15:39:46
【问题描述】:

我必须使用方法 FindResource("key")。在我的 MainWindow 类中,它可以工作。

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

所以,我在我的 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();
}

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

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

【问题讨论】:

    标签: c# xml wpf static resources


    【解决方案1】:

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

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

    【讨论】:

    • 我明年就要结婚了,但是……我想我爱你! :D 啊哈……抱歉这个愚蠢的问题,我是新手,我快疯了……谢谢你的完美提示! :)
    猜你喜欢
    • 2013-05-03
    • 2011-04-10
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2017-06-15
    相关资源
    最近更新 更多