为什么Xaml在运行时而非在编译时反序列化?

时间:2018-10-16 20:37:13

标签: c# wpf xaml baml

在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不采用这种方法? 谢谢;

0 个答案:

没有答案
相关问题