1

在 WPF 中,xaml 文件被编译成称为 baml 的二进制格式。在编译时,名为“PresentationBuildTasks”的工具会生成一个代码隐藏部分类,其中包含用于加载资源 (.baml) 并设置内部属性和事件的逻辑:

这是我的简化 xaml:

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

生成的代码隐藏方法:

    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;
    }

那么为什么 wpf 首先需要从 xaml 生成代码隐藏,然后在运行时加载 baml?如果它像这样在编译时生成整个方法,会不会更高效:

     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);
    }

目前这行不通,但为什么 wpf 不采用这种方法?谢谢;

4

0 回答 0