2017-06-03 38 views
0

我有一個WPF用戶控件,該控件定義了一些默認樣式和圖像,我希望能夠在運行時使用資源組裝中包含的自定義樣式和圖像來覆蓋它們。在運行時合併WPF ResourceDictionary

的風格和圖像都包含在一個裝配體中的命名Olbert.JumpForJoy.DefaultResources稱爲DefaultResources.xaml的ResourceDictionary:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        x:Name="J4JResources"> 

    <BitmapImage x:Key="J4JMessageBoxImage" UriSource="assets/j4jmsgbox.png" /> 
    <BitmapImage x:Key="J4JWizardImage" UriSource="assets/j4jtransparent.png" /> 
    <Color x:Key="J4JButton0Color">#bb911e</Color> 
    <Color x:Key="J4JButton1Color">#252315</Color> 
    <Color x:Key="J4JButton2Color">#bc513e</Color> 
    <Color x:Key="J4JButtonHighlightColor">Orange</Color> 

</ResourceDictionary> 

爲了提供這樣的一個應用程序,我想補充創建時該資源的NuGet包項目編譯到使用自定義資源的應用程序。我已經確認dll被添加到目標bin目錄。

我嘗試加載自定義資源裝配在App.xaml.cs文件中,OnStartup()方法中:

public partial class App : Application 
{ 
    public const string ResourceDll = "Olbert.JumpForJoy.DefaultResources"; 

    protected override void OnStartup(StartupEventArgs e) 
    { 
     try 
     { 
      var resDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{ResourceDll}.dll"); 

      if (File.Exists(resDllPath)) 
      { 
       var resAssembly = Assembly.LoadFile(resDllPath); 
       var uriText = $"pack://application:,,,/{resAssembly.GetName().Name};component/DefaultResources.xaml"; 

       ResourceDictionary j4jRD = new ResourceDictionary { 
         Source = new Uri(uriText) 
        }; 

       Resources.MergedDictionaries.Add(j4jRD); 
      } 
     } 
     catch (Exception ex) 
     { 
     } 
    } 
} 

但在創建資源字典時,一個異常被拋出。該消息是「無法找到資源defaultresources.xaml'」。

我已經嘗試了很多uri定義的調整來解決這個問題,但都沒有工作。資源程序集是版本控制的,但是否在uri定義中包含特定的版本,我得到了同樣的錯誤。

如果將可選資源組合合併到WPF項目中有不同的方式,我很樂意聽到它。我的具體問題的答案,將不勝感激,太:)

更新

如果我試圖通過App.xaml中做到這一點:

<ResourceDictionary.MergedDictionaries> 
    <ResourceDictionary Source="pack://application:,,,/Olbert.JumpForJoy.DefaultResources;component/DefaultResources.xaml" /> 
    <ResourceDictionary Source="NotifyIconResources.xaml"/> 
</ResourceDictionary.MergedDictionaries> 

我得到一個設計時錯誤「找到資源字典時發生錯誤...「

在我的原始方法中調用resAssembly.GetManifestResourceNames()顯示資源確實存在於自定義程序集中。但他們似乎組裝的默認命名空間「下」:

Olbert.JumpForJoy.WPF.DefaultResources.xaml

這使我想知道如果我需要指定該命名空間,不知何故,在定義烏里。

+0

如果直接在您的合併外部資源是否錯誤出現'''中App.xaml'? – Maxim

回答