2017-03-07 123 views
1

我有一個WPF用戶控件庫項目。 在這同一個項目我有一個資源文件,我包括在我的用戶控制資源是這樣的:訪問WPF用戶控件庫中的應用程序資源

<UserControl.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="../Styles/Globals.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</UserControl.Resources> 

如何從代碼中訪問該資源的背後? 當我嘗試訪問Application.Current.Resources時,它是空的。

感謝

編輯: 我意識到,這是因爲資源是用戶控制的成員,而不是一個應用程序的成員。 (在用戶控件庫項目中,我無法在應用程序級別添加資源)。

但是,因爲我使用MVVM,我沒有從我的viewmodel到用戶控件的訪問,所以我如何才能達到用戶控件的資源中的樣式?

回答

0

您可以訪問的樣式像

Style style = Application.Current.FindResource("ResourceName") as Style; 

其中 '資源名稱' 是 '樣式/ Globals.xaml'

+0

我試過了,但它不起作用!它在WPF項目中的正常 工作正常,但在用戶控制庫項目中不起作用 – Hana

0

事情是這樣的工作對我來說:

<Application x:Class="MyApp.App" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     StartupUri="MainWindow.xaml"> 
<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="pack://application:,,,/MyLibraryNamespace;component/rdImages.xaml" /> 
      <ResourceDictionary Source="pack://application:,,,/MyLibraryNamespace;component/rdColorImages.xaml" /> 
      <ResourceDictionary Source="/rdStyles.xaml" /> 
      <ResourceDictionary Source="/rdStringResourceEN.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

前兩個資源字典來自外部庫(樣式,繪圖筆刷),最後兩個是lo cal(包含在我的項目中 - 樣式,字符串)。

+0

在用戶控件庫項目中,我沒有app.xaml文件,並且無法在應用程序級別聲明資源 – Hana

相關問題