2015-11-02 70 views
3

我有一個Windows 10通用應用程序,包含一些樣式等資源字典。 在一個這樣的資源字典中,我有一個顏色,我想通過後面的代碼訪問MyBlue。這是如何實現的?從ResourceDictionary中檢索代碼後面的代碼

我試過this.Resources["MyBlue"],但由於MyBlue是在單獨的資源字典中定義的,而不是直接在頁面資源中定義,所以它不存在於這個集合中。

這裏是我的App.xaml:

<Application.Resources> 

    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="Styles/PodStyles.xaml"/> 
      <ResourceDictionary Source="Styles/ButtonStyles.xaml"/> 
      <ResourceDictionary Source="Styles/OfferStyles.xaml"/> 
      <ResourceDictionary Source="Styles/MyStyles.xaml"/> 

      <ResourceDictionary> 
       <!--Global View Model Locator--> 
       <vm:ViewModelLocator x:Key="Locator" 
            d:IsDataSource="True"/> 
      </ResourceDictionary> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 

</Application.Resources> 

回答

2

MergedDictionaries通過Application.Current.Resources.MergedDictionaries可用。

我能夠獲得由烏里適當的資源字典,然後通過鍵名訪問該項目它:

var mergedDict = Application.Current.Resources.MergedDictionaries.Where(md => md.Source.AbsoluteUri == "ms-resource:///Files/Styles/MyStyles.xaml").FirstOrDefault(); 
newColor = (Windows.UI.Color)mergedDict["MyBlue"]; 
+0

你能分享你的app.xaml嗎?這不應該是必要的。 – moswald

+0

@moswald補充說。 – earthling

+0

呃......:困惑:我不知道。這看起來是正確的,你應該可以通過查看應用程序的資源來實現它。 – moswald

4

你試過

Application.Current.Resources["MyBlue"] 
+0

有跡象表明,資源集合中沒有任何項目。 – earthling

1

ResourceDictionary要引用已經以某種方式拉入應用程序資源。要麼將它合併到您的Application的資源中(如果它已經足夠常見,足以讓您的應用程序初始化時略有打擊),或者將它合併到您的Page的資源中(輕微擊中首頁初始化)。

您包括外國ResourceDictionaries這個語法:

<Page.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="path/to/resource.xaml" /> 
     </ResourceDictionary> 

     <... your other resources for this page go here .../> 
    </ResourceDictionary> 
</Page.Resources> 
+0

我正在將它合併到我的應用程序資源中。我能夠引用xaml中的資源,但不能在代碼背後。 – earthling

+0

然後'(Color)Application.Current.Resources [「MyBlue」]'應該這樣做。 – moswald

相關問題