2015-11-02 44 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