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.
- <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">
- <StackPanel>
- <Button x:Name="button" Content="Click Me" HorizontalAlignment="Left" Margin="150" VerticalAlignment="Top" Width="75" /> </StackPanel>
- </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#.
- using System.Windows;
- using System.Windows.Controls;
- namespace WPFXAMLOverview {
-
-
-
- public partial class MainWindow: Window {
- public MainWindow() {
- InitializeComponent();
- StackPanel stackPanel = new StackPanel();
- this.Content = stackPanel;
-
- Button button = new Button();
- button.Content = "Click Me";
- button.HorizontalAlignment = HorizontalAlignment.Left;
- button.Margin = new Thickness(150);
- button.VerticalAlignment = VerticalAlignment.Top;
- button.Width = 75;
- stackPanel.Children.Add(button);
- }
- }
- }
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.