ResourceDictionary 作为 NuGet 包

ResourceDictionary as NuGet Package

我目前正在尝试创建一种 XAML“样式集”,我们可以在所有 UI 项目中使用它,以实现视觉效果的一致性。

我已经尝试创建一个 class 库并添加了一个 ResourceDictionary 我的风格:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style x:Key="ToggleSwitch" TargetType="{x:Type CheckBox}">
        Some style in here
    </Style>
</ResourceDictionary>

在构建选项中启用构建 NuGet 包并将其添加到另一个 UI 项目。 我只是不太了解如何在 UI 项目中实际使用样式。

这甚至是一种有效的方法吗? 谷歌搜索这个特定的意图并没有给我任何合理的结果。

这是一种有效的方法,它与在本地创建和使用资源字典没有什么不同,不同之处在于如果它们位于引用的程序集中,您如何引用它们。

作为程序集 YourReferencedAssembly.dll 的应用程序资源和直接在程序集中的资源字典 YourStyleResourceDictionary.xaml 的示例。

<Application.Resources>
   <ResourceDictionary>
      <!-- ...other resources. -->
      <ResourceDictionary.MergedDictionaries>
         <!-- ...other resource dictionaries. -->
         <ResourceDictionary Source="pack://application:,,,/YourReferencedAssembly;component/YourStyleResourceDictionary.xaml" />
      </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</Application.Resources>

源码路径是so-calledpack URI and can take various forms. You can refer to the resource file pack URI documentation. This is how the path for resources in referenced assemblies详细看:

Authority: application:///.

Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format:

AssemblyShortName{;Version]{;PublicKey];component/Path

AssemblyShortName: the short name for the referenced assembly.

;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded.

;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded.

;component: specifies that the assembly being referred to is referenced from the local assembly.

/Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder.

Implicit 样式,像往常一样,在添加资源字典的范围内自动应用,并且 explicit 样式被引用或者使用StaticResourceDynamicResource。资源字典的来源没有区别,同一个程序集或不同的程序集。