您能否从编译的角度解释 XAML 文件的生命周期?
当我构建 Silverlight 项目时,构建过程中的 XAML 文件会发生什么情况?
最佳答案
Jon Skeet 对中间 .g.cs 文件的回答(现已删除,但下面为上下文引用的那部分)部分正确,但没有完整回答您的实际问题:
JS: An early part of the build process creates a Foo.i.g.cs file in the obj directory containing a partial class, and that gets compiled in the normal way along with your own .cs files.
.g.cs 文件包含在 InitialiseComponent()
期间将命名元素连接到类成员所需的代码隐藏中缺少的部分。例如这是来自基本的 MainPage.g.cs:
public void InitializeComponent() {
...
System.Windows.Application.LoadComponent(this, new System.Uri("/SilverlightApp1;component/MainPage.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
}
这有点像为 WinForms 控件/对话框生成的设计器文件,但发生在编译时而不是设计时。
- 编译器解析以验证 XAML 并确定需要生成哪些命名元素(到分部类中)。
- XAML 文件本身在构建期间作为资源存储在 DLL 中(在上面的示例中,它存储为
"/SilverlightApp1;component/MainPage.xaml"
) - 注意:仅对于 WPF,嵌入式 XAML 文件实际上被转换为内存效率更高的二进制版本,称为 BAML 文件。
在回答您对 Jon Skeet 的评论(现已删除)时,您的提问部分正确:
So parsing the whole XAML document -all the elements, attributes etc.- is not part of the WPF or SL builds? Am I correct?
除了上面提到的解析之外,对于验证和命名元素,其余解析(元素树和模板等)实际上在运行时完成 LoadComponent()
有效地反序列化 XAML 并创建您创作的元素的可视化树。
关于c# - 当我构建 Silverlight 项目时,XAML 文件会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10971249/