【问题标题】:Differences between WPF Custom Control Library and plain Class Library?WPF自定义控件库和普通类库的区别?
【发布时间】:2010-01-18 20:39:21
【问题描述】:

几个月前我发布了一个关于sharing resource dictionaries across assemblies 的问题。事实证明,您可以使用 Component Resource Key 标记扩展来做到这一点。当时,我只能使用 WPF 自定义控件项目,而不是普通的类库项目。

现在我需要使用现有的普通类库项目来托管共享资源字典。这意味着我需要改造类库项目以支持组件资源密钥标记扩展。我在类库项目中添加了一个 Themes 文件夹和一个 Generic.xaml 资源字典文档,以及对 PresentationCore、PresentationFramework 和 WindowsBase 的引用。不幸的是,这似乎不起作用。

所以,这是我的问题:除了上述之外,WPF 自定义控件库项目还有什么是普通类库项目没有的?或者,换一种说法,我还能在我的类库项目中添加什么来让这个功能正常工作?谢谢。

【问题讨论】:

  • 组件资源密钥标记扩展不起作用。我设置了两个相同的解决方案,一个带有自定义控件库,另一个带有带有 DLL 引用和 Themes/Generic.xaml 的普通类库。组件资源键标记扩展在自定义控件库中有效,但在类库中无效。
  • 我已经通过用自定义控件库替换旧的类库并将所有类从类库移动到自定义控件库来解决这个问题。但我仍然想弄清楚如何改造类库,因为我可能会再次遇到这种情况。
  • 很奇怪。以下对我有用:创建一个类库项目,添加 WPF DLL 引用,添加一个 Themes/Generic.xaml(没有资源字典选项,因此创建为 UserControl 并将 XAML 编辑为 ResourceDictionary),在一个类中创建一个 CRK(基于在您链接的问题上),向 generic.xaml 添加了一个资源,其中 x:Key 设置为该 CRK。对我来说编译得很好(VS2008 SP1)。我不需要 Cameron 提到的 ThemeInfoAttribute。是否值得发布您的 XAML 文件?

标签: wpf


【解决方案1】:

除了额外的 WPF 引用之外,WPF 自定义控件库模板在 AssemblyInfo 中还有一个额外的属性。

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
    //(used if a resource is not found in the page, 
    // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
    //(used if a resource is not found in the page, 
    // app, or any theme specific resource dictionaries)
)]

ThemeInfoAttribute 指定为程序集中的类型存储主题字典的位置。

【讨论】:

  • 请注意,我没有测试过这个解决方案,但它确实是有道理的。我希望缺少该属性来禁用 Themes/generic.xaml 支持。
【解决方案2】:

Cameron MacFarland 的回答很到位。我现在已经对其进行了测试,并且可以正常工作。

解决方案如下:将 DLL 引用和 Themes/generic.xaml 文件添加到普通类库项目中。然后,打开 AssemblyInfo.cs 并在文件末尾添加以下代码:

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
    //(used if a resource is not found in the page, 
    // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
    //(used if a resource is not found in the page, 
    // app, or any theme specific resource dictionaries)
)]

重新编译,组件资源密钥标记扩展应该可以工作。

【讨论】:

【解决方案3】:

另一个区别在于 .csproj 文件:

类库中缺少标签:

<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

将其添加到第一个 PropertyGroup 后,项目的添加菜单现在显示典型的 WPF 文件。

【讨论】:

    猜你喜欢
    • 2014-06-11
    • 2023-01-07
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多