我有一个棱镜应用程序和各种模块。我想知道最好的地方放置样式、画笔、控件模板和数据模板等资源?
我应该创建一个单一的资源字典,把所有东西都放在那里吗?每个模块都应该有它们自己的资源吗?或者每个视图都应该有它们自己的资源?我想遵循棱镜的目标,即保持一切模块化,但我也不明白在每个模块中重新声明相同的资源有什么意义......
我使用Prism开发应用程序,并且我使用了与Prism手册中描述的非常接近的技术。通常在 YourApplication.Infrastructure 项目中放置所有共享接口等内容。因此:
创建名为 Themes\Generic.xaml 的文件(确切地使用这个名称,在未来将带来巨大的好处),并编写以下内容:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Generic.Brushes.xaml"/>
<ResourceDictionary Source="Generic.WPF.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
现在,您可以通过将对 YourApplication.Resources 的引用添加到该项目的任何模块(您有单独的项目用于此,对吧?)并将其添加到您的视图的 xaml 中,来添加这些资源: <UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/YourApplication.Resources;component/Themes/Generic.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!-- Put your not shared resource here -->
</ResourceDictionary>
</UserControl.Resources>
我不知道,也许这种方法存在一些问题,但它可以工作,并且对我来说效果很好。如果有人可以评论一下使用这种方法的优缺点,我会非常高兴听到!我通常将应用程序范围的资源放在 ResourceDictionary
中,这个字典会被添加到 App.xaml
或 StartupWindow.xaml
中。
特定视图的资源通常位于该视图中。例如,用于日历视图的 UserControl 将包含任何用于日历的自定义资源,例如特定于日历的画刷、样式、模板等。
我通常不需要制作模块范围的资源,但如果确实需要,我会为该模块创建一个 ResourceDictionary
,可以在运行时将其加载到应用程序的合并字典中,或者包含在模块中的各个视图中。
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/YourApplication.Resources;component/Themes/Generic.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!-- Put your not shared resource here -->
</ResourceDictionary>
</UserControl.Resources>
然后在你的Bootstrapper
的App.xaml
中声明<ResourceDictionary/>
就可以了:
<Application.Resources>
<ResourceDictionary Source="pack://application:,,,/YourApplication.Resources;component/Themes/Generic.xaml"/>
</Application.Resources>