簡體   English   中英

在C#類庫項目中使用(合並)資源字典

[英]Using (merged) Resource Dictionary in C# Class Library Project

如何在C#類庫項目中使用(合並的)WPF資源字典?

這是我做的:

在我的C#類庫項目中,我有一個類似的文件Dictionary1.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                >
    <Style x:Key="PluginFrameBorderStyle">
    ...
    </Style>
</ResourceDictionary>

然后,我有一個UserControl文件UserControl1.xaml ,我嘗試使用這樣的字典:

<UserControl x:Class="EditorPackageA.BackboneMemberB1Editor.BackboneMemberB1Editor"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         xmlns:local="clr-namespace:EditorPackageA.EditorBase"
         xmlns:prism="http://www.codeplex.com/prism" d:DesignWidth="690.4" d:DesignHeight="460.12">
<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/Dictionary1.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</UserControl.Resources>
...
</UserControl>

該項目編譯但在運行時我得到錯誤:

在此輸入圖像描述

除了細節:

在此輸入圖像描述

WPF項目中應用時,相同的方法也適用,而不是類庫項目

這可能是什么解決方案?

重要附錄:

在設計期間,我看到通過ResourceDictionary嵌入的使用樣式的效果,因此樣式的URI和字典必須正確!?

嘗試使用所謂的pack URI。 我認為您必須明確指定資源字典的位置。

<ResourceDictionary Source="pack://application:,,,/TheNameOfClassLibrary;component/Dictionary1.xaml"/>

對於WPF項目,您的方法可行,因為WPF引擎默認查找正在執行的程序集中的資源(在exe中)。

您可能需要在應用程序資源中合並庫的資源字典。 您需要編輯App.xaml文件並添加如下內容:

<Application.Resources>
<ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
      <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Dictionary1.xaml" />
      </ResourceDictionary.MergedDictionaries>
  </ResourceDictionary>
</Application.Resources>

您應該使用程序集和組件名稱將ResourceDictionary xml文件引用/鏈接到Source屬性。
使用相對路徑如下:

<ResourceDictionary Source="../Dictionary1.xaml" /> 

如果它不起作用,請嘗試PACK URL

<ResourceDictionary Source="pack://application:,,,/Your.Base.AssemblyName;component/DictionaryFolder/Dictionary1.xaml" />

希望它能幫到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM