【问题标题】:Use Resource Dictionary Styles in my class library project without merging dictionaries在我的类库项目中使用资源字典样式而不合并字典
【发布时间】:2014-12-10 21:44:34
【问题描述】:

我正在创建一个包含 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>
    

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

【问题讨论】:

  • 您可以尝试将程序集的公共资源放入Themes\Generic.xaml 资源字典(将构建操作设置为“页面”)。这就是 WPF 期望控件库的默认、独立于主题的样式的地方,因此这些资源应该自动加载到您的应用程序中。通常,该文件实际上并不声明任何资源,而是使用MergedDictionaries 从其他文件中提取资源。
  • 为什么不在您的解决方案中有一个 wpf 项目,并在那里添加您的类库作为参考。从那里您可以调用用户控件或普通窗口作为您的启动屏幕
  • 请参考stackoverflow.com/a/46258276/417939。简而言之,类库在设计时和运行时都可以使用启动应用程序中定义的应用程序资源。

标签: wpf resources resourcedictionary


【解决方案1】:

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

Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml">

或者简单如下:

<UserControl.Resources>
    <ResourceDictionary Source="pack://application:,,,/ControlsDLL;component/ResourceDictionary1.xaml"></ResourceDictionary>
</UserControl.Resources>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-21
相关资源
最近更新 更多