在 WPF 中,Generic.xaml 是一个特殊的资源文件,它会被自动加载,不需要显式添加。这是 WPF 的命名约定。当 WPF 初始化自定义控件时,它会专门查找这个名字的文件。
这个名字是硬编码在 WPF 框架中的,不能改变。
Generic.xaml 是 WPF 自定义控件的默认样式位置,只要满足以下条件就会自动加载:
- 文件名必须是 Generic.xaml
- 文件必须在 Themes 文件夹下
- 控件必须正确设置 DefaultStyleKey
条件:
1.AssemblyInfo.cs 文件中包含有以下特性:[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
)]
2.控件库项目的 Themes 文件夹:
YourProject/
└── Themes/
└── Generic.xaml3.自定义控件 CustomControl1的定义:
public class CustomControl1 : Window
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
使用了自定义控件库,检查控件库的项目结构:
CustomControlLibrary/
├── Themes/
│ └── Generic.xaml
├── Controls/
│ └── ExWindow.cs
└── Properties/
└── AssemblyInfo.cs
自动加载的原理:
1.当 WPF 应用程序启动时,框架会扫描所有引用的程序集
2.对于每个程序集,它会检查是否存在 Themes/Generic.xaml
3.如果找到了,会自动将其加载到应用程序的资源系统中
4.当需要为自定义控件查找样式时,WPF 会:
- 首先查看控件的 DefaultStyleKey
- 然后在加载的资源中查找匹配的样式
- 如果在 Generic.xaml 中找到匹配的样式,就应用它
这就是为什么不需要显式添加 Generic.xaml 的原因 - 它是 WPF 控件开发的一个内置约定。