XAML!=WPF
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
If you do a search on any search engine for WPF and then open any of the links, they invariably mention XAML. Similarly, if you create a WPF application in Visual Studio 2008 or C# Express 2008, then default XAML files are created for you. This does not have to be the case.
WPF without XAML
In order to create a WPF application, you do not need to add any XAML code. If you read Charles Petzold's book "Applications = Code + Markup", you will see that he does not cover anything to do with XAML until chapter 19 on page 461. To prove this point, the method below creates an empty WPF application that does not use any XAML.
- Create a new empty project.
- Add a new class to the project.
- Add the following references to the project.
-
WindowsBase -
PresentationCore -
PresentationFramework
-
An application written for the Microsoft Windows Presentation Foundation (WPF) begins by creating objects of type Application and Window. Add the following code to the class:
[STAThread] public static void Main() { Window win = new Window(); win.Title = "Hello World"; win.Show(); Application app = new Application(); app.Run(); }
Press F5 to compile and run the application and a new application runs with the title "Hello World". You should have noticed that a console window was also running behind the window application. This is because an empty project defaults to a console window. To rectify this, open the project properties and change the output type to "Windows Application".
Analysing the code
In any WPF program, the [STAThread] attribute must precede Main or the C# compiler will complain. This attribute directs the threading model of the initial application thread to be a single-threaded apartment, which is required for interoperability with the Component Object Model (COM).
Any WPF application can only create one Application object, which exists as a constant anchor for the rest of the
program.
You can create the Application object before creating the Window object, but the call to Run must be last in the Main method. The Run method does not return until the window is closed at which point, the Main method ends and Windows cleans up after the applciation. If you remove the call to Run, the Window object is still created and displayed, but it is immediately destroyed when Main ends.
WPF with XAML
When you create a WPF application, you are presented with an XAML window as per the following screen shot.
To achieve the same application as we created earlier, simply change the XAML code that looks like this:
Title="Window1" Height="300" Width="300">
to
Title="Hello World" Height="300" Width="300">
Now when you run the application you will see an empty WPF application titled "Hello World".
|




