tags:

views:

34

answers:

2

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?

+2  A: 

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.

Richard
+2  A: 

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

The xaml code is linked with a class.

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

VS generate for you a MainWindow.cs which have 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 MainWinow.xaml even if it's the right class name.

Eventually, for a UserControl you will have the xaml tag <UserControl instead of Window. One more thing, the compiler also, generate at compiling, a file a called MainWindow.g.cs int the obj folder where you can find also MainWindow.baml the compiled version of the xaml file. This file will contain a partial class MainWindow with all the controls declaration that you use in the xaml. That's a behind scene job that do the compiler, but again no magics ;)

For the application is the same only the class type change. This to link xaml with the cs file. For the StartUp Window, it's specified in xaml file by default to a xaml file but you can customized in the cs file and do yo own logic in the ApplicationStartUp event.

Same for the Shutdown, by default it's when all your windows are closed but you can change it to Main window closed or explicit shutdown.

The csproj (in the case of c#) tels the compiler which class is the application one

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

Not only the xaml tag like other said. The tag only define the type of the class and don't make your program start with this specific class.

Application overview

You can read further here : MSDN - Building WPF application

MSDN - Code-Behind and XAML in WPF

MSDN - Application Management Overview

Zied