Dot-Net

我可以在程式碼隱藏中獲得風格的關鍵嗎?(WPF)

  • August 29, 2017

如果我有以下程式碼:

Style defaultStyle = (Style)FindResource("MyTestStyle");

有沒有辦法獲取樣式的名稱(即反向查找)?就像是:

string name = defaultStyle.SomeMagicLookUpFunction()

其中名稱將評估為“MyTestStyle”。

這可能嗎?

我創建了一個小的幫助類,它使用一個方法來執行您需要的反向查找。

public static class ResourceHelper
{
   static public string FindNameFromResource(ResourceDictionary dictionary, object resourceItem)
   {
       foreach (object key in dictionary.Keys)
       {
           if (dictionary[key] == resourceItem)
           {
               return key.ToString();
           }
       }

       return null;
   }
}

您可以使用以下方法呼叫它

string name = ResourceHelper.FindNameFromResource(this.Resources, defaultStyle);

每個FrameworkElement人都有自己的.Resources字典,使用“this”假設您在正確的位置定義 MyTestStyle。如果需要,您可以向靜態類添加更多方法以遞歸遍歷視窗中的所有字典(應用程序?)

引用自:https://stackoverflow.com/questions/538750