1

In WPF xaml files are compiled into a binary format called baml. At compile time a tool called "PresentationBuildTasks" generates a codebehind partial class which contains the logic for loading the resource (.baml) and set the internal properties and events:

Here is my simplified xaml:

  <Window>
    <Grid>
       <Button x:Name="btn" Content="Button" Click="Button_Click"/>
    </Grid>
 </Window>

The generated codebehind methods:

    public void InitializeComponent() {
        if (_contentLoaded) {
            return;
        }
        _contentLoaded = true;
        System.Uri resourceLocater = new System.Uri("/WPFDispatcher;component/mainwindow.xaml", System.UriKind.Relative);

        // here the baml is loaded and deserialised
        System.Windows.Application.LoadComponent(this, resourceLocater);
    }


    void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
        switch (connectionId)
        {
        case 1:
             this.btn = ((System.Windows.Controls.Button)(target));

             this.btn.Click += new System.Windows.RoutedEventHandler(this.Button_Click);

              return;
        }
        this._contentLoaded = true;
    }

So why does wpf first need to generate the codebehind from the xaml but then load the baml at runtime? Wouldn't it be more performant if it would generate the whole methods at compile time like this:

     public void InitializeComponent() {
        this.btn = ((System.Windows.Controls.Button)(target));
        // Initialize btn with the deserialized properties from xaml

        this.btn.Click += new System.Windows.RoutedEventHandler(this.Button_Click);
    }

Currently this would not work but why does wpf not take this approach? Thanks;

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hakim
  • 452
  • 4
  • 15
  • @Clemens - This is might be a duplicate question but a real and good answer is not given in the [question](https://stackoverflow.com/questions/1423728/why-xaml-is-compiled-into-baml-and-not-in-c-sharp) you are refering to – Hakim Oct 17 '18 at 14:34

0 Answers0