在Visual Studio (2019) 中创建一个C# UWP的Blank App(命名为App1),会自动生成两个XAML文件:

  • App.xaml
  • MainPage.xaml

其中App.xaml的内容基本为空

<Application
    x:Class="App1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1">

</Application>

但是上面的xaml文件指定了一个属性:x:Class="App1.App",这说明此xaml文件是和类App(App1是该类所在的命名空间)结合在一起的,或者说该xaml的部分逻辑是在App类中实现的。App类在App.xaml.cs中定义。

App类是从Windows.UI.Xaml.Application中派生出来的,其定义如下:

    sealed partial class App : Application

上面的partial 关键字说明App.xaml.cs只是部分实现了App类而已。

自动生成的类中有一个默认构造函数,不带任何参数,在这个构造函数中调用了:

            this.InitializeComponent();

这行代码会加载并初始化xaml。

另外一个xaml文件内容也很简单:

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid>
    </Grid>
</Page>

可以看出这个xaml是由App1.MainPage类支持的,这个类是在MainPage.xaml.cs中定义的。MainPage类继承自Windows.UI.Xaml.Controls.Page,其默认构造函数只有一行代码,就是:

            this.InitializeComponent();

用来加载MainPage.xaml。

可能你已经注意到了,App.xaml.cs以及MainPage.xaml.cs中的类都是定义为partial的。这是因为XAML编译之后会生成两个C#文件,一个是.g.cs结尾的,另一个是.g.i.cs结尾的。

以App.xaml为例,编译后生成App.xaml.g.cs和App.xaml.g.i.cs。其中App.xaml.g.i.cs定义了作为函数入口的Main(),以及加载xaml的InitializeComponent()。

(完)