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?
Share
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.
VS generates for you a MainWindow.cs file which has a class named
MainWindowofWindowtype. 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
<UserControlinstead of aWindowtag.One more thing, the compiler also generates at compile time a file called
MainWindow.g.csin theobjfolder where you can also find aMainWindow.bamlthe 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.
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