简体   繁体   中英

How do XAML files associate with cs files?

It seems that XAML files should have corresponding .cs files in a C# project. I know Visual Studio does all the things for us. I'm just curious how they are linked together? I mean, are they specified in the project file, or just because they have the same names? And also, App.xaml file specifies the startup file, but how does the compiler know? Is it possible to appoint another file other than App.xaml to do the same things as App.xaml does?

There's no magic happening in WPF. All what happen is written some where. It's VS which generates some of the code.

The xaml code is linked with a class.

<Window x:Class="YourNameSpace.MainWindow" ...

VS generates for you a MainWindow.cs file which has a class named MainWindow of Window type. The type is important here. If you use another type the compiler won't link it to your MainWindow.xaml even if it's the right class name. Eventually, for a UserControl you will have the xaml tag <UserControl instead of a Window tag.

One more thing, the compiler also generates at compile time a file called MainWindow.g.cs in the obj folder where you can also find a MainWindow.baml the compiled version of the xaml file. This file will contain a partial class MainWindow with all the controls declared that you use in the XAML. That's a behind the scene job that the compiler does which is unrelated to the association between the XAML and the relative class.

The application is the same, only that the class type changes. This is to link XAML with the class. For the StartUp Window, it's specified in the XAML file by default to a class. However, you can customize the .cs file and do yo own logic in the ApplicationStartUp event.

Same for the Shutdown event. By default it's when all your windows are closed but you can change it to when the MainWindow is closed or an explicit shutdown.

The csproj (in the case of c#) tells the compiler which class is the application.

<ApplicationDefinition Include="App.xaml">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
</ApplicationDefinition>

Not only the XAML tag like others have stated. The tag only defines the type of the class and don't make your program start with this specific class.

应用概述
(source: microsoft.com )

You can read further here : MSDN - Building WPF application

MSDN - Code-Behind and XAML in WPF

MSDN - Application Management Overview

The code behind defines a class derived from Window , UserControl , ... and then the XAML's root element references that type with the x:Class attribute.

The App.xaml is the startup, because it is has an <Application> root element, using the same mechanism to reference the code behind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM