在我的类库项目中使用资源字典样式而不合并字典

Ton*_*Nam 5 wpf resources resourcedictionary

我正在创建一个包含 WPF 用户控件的类库项目。我的要求是所有控件都具有相同的样式。我的项目看起来像:

在此处输入图片说明

为了解决这个问题,我所做的事情:

  1. 添加了 WPF 应用程序System.Xaml、WindowsBase 等所需的所有引用以便我可以在我的类库项目中拥有 wpf 控件。
  2. AssemblyInfo.cs 中,我添加了:

    [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]

  3. ResourceDictionary1.xaml添加到添加样式的项目中。

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <SolidColorBrush x:Key="Brush1" Color="#FF19199E"/>
    </ResourceDictionary>

  4. 现在,如果我想在UserControl1.xaml上使用样式,我会这样做:

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ResourceDictionary1.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    
    </UserControl.Resources>
    
    <Grid >
        <Rectangle Fill="{StaticResource Brush1}"  />
    </Grid>
    
    Run Code Online (Sandbox Code Playgroud)

我知道它很好用,但这里有一个问题。每次我创建一个新的 userControl 时,我都必须合并字典。在常规 WPF 应用程序中,我只需在 App.xaml 上合并字典一次,就可以在整个应用程序中使用该字典。如何避免每次创建新用户控件时都必须合并字典?如果我打算添加一个新的资源字典,我将不得不转到所有 userControls 并合并另一个字典。也许我写错了问题标题,我的问题应该是如何将 App.xaml 文件添加到类库项目

小智 -1

ResourceDictionary1.xaml您应该像下面这样替换源值:

Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml">
Run Code Online (Sandbox Code Playgroud)

或者简单如下:

<UserControl.Resources>
    <ResourceDictionary Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml"></ResourceDictionary>
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)