Why XAML In WPF

XAML is not only the most widely known feature of WPF; but it's also one of the most misunderstood features. If you have exposure to WPF, then you must have heard of XAML; but take a note of the two less known facts about XAML, whicch are given below.

  • WPF doesn't need XAML.
  • XAML doesn't need WPF.

They are in fact separable pieces of technology. To understand how this can be, let's look at a simple example in which a button is created with some properties in XAML. 

  1. <Window x:Class="WPFXAMLOverview.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="604">  
  2.     <StackPanel>  
  3.         <Button x:Name="button" Content="Click Me" HorizontalAlignment="Left" Margin="150" VerticalAlignment="Top" Width="75" /> </StackPanel>  
  4. </Window>   

If you choose not to use XAML in WPF, then you can achieve the same GUI result with procedural language as well. Let’s have a look at the same example, but this time, we will create a button in C#. 

  1. using System.Windows;  
  2. using System.Windows.Controls;  
  3. namespace WPFXAMLOverview {  
  4.     /// <summary>  
  5.     /// Interaction logic for MainWindow.xaml  
  6.     /// </summary>  
  7.     public partial class MainWindow: Window {  
  8.         public MainWindow() {  
  9.             InitializeComponent(); // Create the StackPanel  
  10.             StackPanel stackPanel = new StackPanel();  
  11.             this.Content = stackPanel;  
  12.             // Create the Button  
  13.             Button button = new Button();  
  14.             button.Content = "Click Me";  
  15.             button.HorizontalAlignment = HorizontalAlignment.Left;  
  16.             button.Margin = new Thickness(150);  
  17.             button.VerticalAlignment = VerticalAlignment.Top;  
  18.             button.Width = 75;  
  19.             stackPanel.Children.Add(button);  
  20.         }  
  21.     }  
  22. }   

When you compile and execute either XAML code or C# code, you will see the same output, as shown below.

From the example given above, it is clear that what you can do in XAML to create, initialize and set properties of the objects, the same tasks can also be done, using code.

  • XAML is just another simple and easy way to design UI elements.
  • With XAML, it doesn’t mean that what you can do to design UI elements is the only way. You can either declare the objects in XAML or define them using code.
  • XAML is optional, but despite this, it is at the heart of WPF design.
  • The goal of XAML is to enable visual designers to create user interface elements directly.
  • WPF aims to make it possible to control all visual aspects of the user interface from mark-up.
Ebook Download
View all
Learn
View all