#105 – Viewing BAML as XAML

BAML is simply a compiled binary version of a XAML fragment.  The XAML elements are converted into equivalent binary objects.  This means that translating back from BAML to XAML is straightforward.

The simplest way to view a particular .baml file as XAML is to use the .NET Reflector tool.  After you download the tool, download the BamlViewer add-in for Reflector.  You’ll have to install the add-in (View | Add-Ins | Add).

Once installed, you just open the executable that contains the BAML, stored as a resource.  Then open the BAML Viewer from the Tools menu.

The BAML Viewer window will open and you can then navigate to the .baml that you want to examine (found embedded as a resource).  When you select the .baml file in the upper pane, the equivalent XAML will be displayed in the lower pane.

Advertisements

#101 – What Visual Studio Does with Your XAML

Given that XAML is just a declarative representation of the objects used by your WPF application, the objects need to be instantiated at runtime.

Here’s the process (e.g. for MainWindow.xaml):

  • While you work in designer, VS2010 automatically generates partial class (e.g. MainWindow.g.i.cs), including:
    • Reference variables for named elements in XAML  (e.g. myButton)
    • Code to instantiate XAML objects at runtime
  • When you build the project
    • All code (yours and VS2010-generated) is compiled
    • XAML is compiled into BAML (binary), stored in .baml file
    • All BAML files combined into single .g.resources file (e.g. MyApp.g.resources)
    • Executable is built, embedding the .g.resources file as a resource
  • At runtime
    • Window constructor calls InitializeComponent
    • InitializeComponent (in generated code) calls Application.LoadComponent, passing URI identifying XAML
    • LoadComponent loads binary XAML from embedded resource, creates all objects
    • As BAML is read, window’s IComponentConnector.Connect method is called, which hooks up local object references to the created objects and attaches event handlers

#62 – BAML is Compiled XAML

When you create a WPF application, you create a definition of the user interface in XAML, rather than in code.  This separates the definition of the structure of the user interface from its behavior.  The XAML is then parsed at runtime and used to create all of the objects that it describes.

Because XAML is rather verbose, it could be costly/slow to read and parse it at runtime.  Because of this, Visual Studio compiles all XAML into a binary version of the same information.  This is stored as a BAML (Binary Application Markup Language) file.

The resulting BAML file is stored as a resource with your .DLL or .EXE.  Because it is binary, it takes up less space.  It’s also quicker to read at runtime, because it has already been parsed and converted into tokens.