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?
-
please dont repeat the tags (C# WPF) in the title. – John Saunders Jun 05 '10 at 14:45
-
1Note, the same mechanisms are used to associate VB code behind in a WPF+VB project, there is nothing here that is C# specific (providing you replace ".cs" is example filenames to ".vb"). – Richard Jun 05 '10 at 15:37
2 Answers
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

- 21,988
- 13
- 81
- 109

- 1,696
- 12
- 20
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.

- 106,783
- 21
- 203
- 265