canahari
canahari

Reputation: 522

Compilation of XAML files (WPF)

I would like to understand the compilation process of XAML files. Sorry for putting this question here but I really did not find any resource explaining this process in-depth.

I understand that XAML is compiled into a .baml file. But: Is the .baml compiled from the generated .g.cs file? Or is the .baml independent and is the IL code generated from the generated .g.cs AND the original .xaml.cs file - this would explain why MainWindow is partial. Which parts of the XAML declarations go into the BAML file? I would like to know also when the loading of a .baml file takes place (for example when talking about a window). Thanks for the help.

Upvotes: 15

Views: 11498

Answers (1)

har07
har07

Reputation: 89285

In my understanding based on the reference below, everything declared in XAML gets compiled to BAML; .g.cs and .xaml.cs files compiled to IL; .xaml.cs IL generated from codes in .xaml.cs file (obviously), and g.cs IL contains codes generated to interact with BAML (instead of IL codes generated from BAML it self).

Check this blog post for reference. To summarize, the author said that compilation of XAML happened in 2 steps :

Step 1. The first step is to compile the XAML files into BAML using the xamlc.exe compiler. For example, if our project includes a file name Window1.xaml, the compiler will create a temporary file named Window1.baml and place it in the obj\Debug subfolder (in our project folder). At the same time, a partial class is created for our window, using the language of our choice. For example, if we’re using C#, the compiler will create a file named Window1.g.cs in the obj\Debug folder. The g stands for generated.

The partial class includes three things:

• Fields for all the controls in our window.

• Code that loads the BAML from the assembly, thereby creating the tree of objects. This happens when the constructor calls Initialize Component ().

• Code that assigns the appropriate control object to each field and connects all the event handlers. This happens in a method named Connect (), which the BAML parser calls every time it finds a named object.

Step 2. When the XAML-to-BAML compilation stage is finished, Visual Studio uses the appropriate language compiler to compile our code and the generated partial class files. In the case of a C# application, it’s the csc.exe compiler that handles this task. The compiled code becomes a single assembly Window1.exe) and the BAML for each window is embedded as a separate resource.

Upvotes: 10

Related Questions