WPF Overview — Programming languages part 1

WPF uses XAML to “declaratively define the UI” and C# to define the behavior of the application.

1. XAML

  • XAML is an XML based markup language used to define the UI which makes up the element tree of a WPF application. This is similar to the DOM (Document Object Model) in web applications.
  • XAML can be used to define UIs for other platforms apart from WPF, however this guide focuses on XAML for WPF.

1. 1. XAML syntax

  • Similar to HTML, each element tag must have an opening and closing tag unless of if it is a self closing tag as shown in the example below:
#. Button is a self closing tag<StackPanel> 
<Button Content="Click Me"/>
</StackPanel>
  • An element tag can also have attributes such as “Content” inside the button tag above.
  • It also helps to think about element tags as CLR(Common Language Runtime) Objects and the attributes as properties of those objects.
  • The final UI of the application is processed as tree element such as the one shown below:
Element tree example — Taken from https://www.tutorialspoint.com/wpf/wpf_elements_tree.html
  • Not all properties can be specified as ‘strings’. Hence you can also specify properties using markup extensions or as content properties as shown by the examples below:
# Set the Children property as a "Content" property# Imagine having to do this: <StackPanel Children="<Button/>" />??!!# This is definitely better!<StackPanel>     
<StackPanel.Children>

<Button>First Button</Button>
<Button>Second Button</Button>
</StackPanel.Children>
</StackPanel>
# Set Style property using Markup extentions within {}<Button Content="Submit" Style="{StaticResource PageBackground}"/>

1.2. XAML Namespaces

  • Each xaml file has exactly one root element with a default namespace as well as factory or user defined custom namespaces.
<Window    #1. Default namespace
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
# 2. Factory defined custom namespace
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!-- UI elements --></Window>
  • Remember that all tags represent CLR objects , hence the default namespace, “tells” the XAML processor where the internal tags such as Window, Page, User-control etc. are defined.
  • It is also possible to define a custom xaml namespace, in order to refrence the controls or objects defined in that namespace.

1.3. Attached properties

  • Another common feature in WPF XAML is the attached properties
  • Just as the name insinuates, it allows an property to be attached to a type even though it does not exist in the types class definition
# Grid.Row is an attached property that tells the grid where to #position the child element inside the grid.<Grid><TextBlock Grid.Row="0" Text="Atach something on me"/></Grid>
  • Internally this is implemented as a dependency property in the TextBlock class. (More on this later)

--

--