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;