π Lecture 12 β Windows Presentation Foundation (WPF)
π Overview: This lecture introduces Windows Presentation Foundation (WPF), a modern UI framework for building rich, visually polished Windows applications. It covers WPF's history, key features, comparison with earlier technologies, the role of XAML, and the evolution of WPF versions. Understanding WPF is essential for creating modern, designer-friendly, and hardware-accelerated user interfaces.
ποΈ Topics Covered
This lecture begins with the history and evolution of WPF from its 2003 codename "Avalon" to WPF 4.0 in 2010. It then explores the highlights of WPF including broad integration, resolution independence, hardware acceleration, declarative programming with XAML, and rich composition. The lecture compares WPF with earlier UI technologies like Win32, GDI, GDI+, Windows Forms, and DirectX. It discusses new features in WPF 3.5/3.5SP1 and WPF 4.0, contrasts WPF with Silverlight, and introduces XAML as a declarative markup language for describing interfaces.
π Lecture Summary
Chapter 12 β Lecture 12: Windows Presentation Foundation (WPF)
WPF (Windows Presentation Foundation) was publicly announced in 2003 under the codename "Avalon." WPF 4.0 was released in April 2010. It has a steep learning curve because code must be written in many places, and there are multiple ways to perform a particular task. WPF enables polished user interfaces that receive significant attention, allows rapid iterations and major interface changes throughout development, and keeps user interface description separate from implementation. Developers can create an "ugly" application that designers can re-theme, which is difficult in the Win32 style of programming where code to re-paint the user interface is mixed with program logic.
Earlier UI technologies include GDI (Graphics Device Interface), introduced in Windows 1.0 in 1985; OpenGL, a leap ahead introduced in the 90s; DirectX, introduced in 1995 with DirectX 2 in 1996; GDI+, a newer library based on DirectX also used behind Xbox graphics; Windows Forms, the primary way of UI design in C#; and XNA, which provides a managed library for DirectX and is great for game development (no .NET/COM interoperability required). A simple example is drawing bitmaps on buttons, which can be efficiently done using GDI.
The highlights of WPF are: 1) Broad integration β includes 2D, 3D, video, speech libraries, etc. 2) Resolution independence β WPF emphasizes vector graphics. 3) Hardware acceleration β based on Direct3D, but can work using a software pipeline if Direct3D hardware is not available. 4) Declarative programming β using Extensible Application Markup Language (XAML, pronounced "Zammel"). Custom attribute and configuration files have always existed, but XAML is very rich. 5) Rich composition and customization β for example, you can create a combobox filled with animated buttons or a menu filled with live video clips, and it is quite easy to skin applications.
π‘ Why this matters: WPF's rich composition allows developers to embed interactive elements (like animated buttons or live video) directly into standard UI controls, enabling highly dynamic and visually engaging applications that were previously difficult to build.
In short, WPF aims to combine the best attributes of systems such as DirectX (3D and hardware acceleration), Windows Forms (developer productivity), Adobe Flash (powerful animation support), and HTML (declarative markup). The first release in November 2006 was WPF 3.0 because it shipped as part of the .NET Framework 3.0. WPF 3.5 came a year later. The next version as part of .NET 3.5 SP1 came in August 2008. The WPF Toolkit, released in August 2008, was experimental and has quick releases. Regarding tool support, WPF extensions for Visual Studio 2005 arrived a few months after the first WPF release, along with a public release of Expression Blend. Now, Visual Studio 2012 is a first-class WPF development environment, mostly rewritten using WPF, and Expression Blend is 100% WPF and great for designing and prototyping WPF apps.
New features in WPF 3.5/3.5SP1 include: Interactive3D with 2D elements in 3D scenes; first-class interoperability with DirectX; better data binding using XLINQ; better validation and debugging (reducing code); better special effects; high-performance custom drawing; text improvements; enhancements to partial-trust apps; improved deployment; and improved performance.
New features in WPF 4.0 include: multi-touch support β compatible with Surface API v2; Windows 7 support like jump lists and new common dialogs; new controls like DataGrid and Calendar; easing animation functions (bounce, elastic); enhanced styling with Visual State Manager; improved layout on pixel boundaries; non-blurry text (with some limitations, so must opt-in); deployment improvements; and performance improvements.
Silverlight vs WPF
Silverlight is a lightweight version of WPF for the web. It chose to follow the WPF approach. First released in 2007, version 4 was released in April 2010, near WPF 4. There is often confusion about when to use one or the other. Both can run in and outside the web. Silverlight is mostly a subset of WPF, but there are some incompatibilities. Decisions include: should I use full .NET or partial .NET, and should I have the ability to run on other devices (e.g., Macs)? Ideally, a common codebase should work for both, but currently the best approach is using #ifdefs to handle incompatibilities.
π Definition β Silverlight: A lightweight version of WPF designed for web applications, mostly a subset of WPF with some incompatibilities. It can run on other platforms like Macs.
π Example: If you want to run your application on both Windows and Mac, you might use Silverlight. To handle differences between WPF and Silverlight code, you can use #ifdef SILVERLIGHT in your C# code to conditionally compile platform-specific sections.
XAML β Extensible Application Markup Language
XAML is primarily used to describe interfaces in WPF and Silverlight. It is also used to express activities and configurations in Workflow Foundation (WF) and Windows Communication Foundation (WCF). XAML is a common language for programmers and other experts, such as UI design experts. Field-specific development tools can be created. Field experts are graphic designers, who can use a design tool such as Expression Blend. Beyond coordinating with designers, XAML is good for a concise way to represent UI or hierarchies of objects, encourages separation of front-end and back-end, provides tool support with copy and paste, and is used by all WPF tools.
π Definition β XAML: An XML-based declarative programming language for creating and initializing objects. It is a way to use .NET APIs. It has few keywords and elements, and it does not make sense without .NET, just as C# does not make sense without .NET. Microsoft formalized XAML vocabularies, such as the WPF XAML vocabulary.
π Example: Instead of writing C# code to create a button, you can write in XAML:
<Button Content="Click Me" Width="100" Height="30"/>
This declaratively creates and initializes a Button object with specified properties.
Comparisons with SVG and HTML are misguided. XAML is XML with a set of rules. Online specifications for the XAML object specification language and WPF and Silverlight vocabularies are available. XAML is used by other technologies as well, although it was originally designed for WPF. Using XAML in WPF projects is optional β everything can be done in procedural code as well, although it is rare to find it done that way.
β Key Takeaways
WPF is a modern UI framework that integrates 2D, 3D, video, and speech, emphasizes vector graphics for resolution independence, and uses hardware acceleration via Direct3D. Its declarative programming model using XAML separates UI design from code, enabling designers and developers to work collaboratively. Key versions include WPF 3.0 (2006), 3.5 (2007), and 4.0 (2010) with multi-touch and Windows 7 support. Silverlight is a lightweight subset for web, mostly compatible but requiring #ifdef for platform differences. XAML is an XML-based declarative language essential for describing WPF interfaces but is optional β all tasks can be done in procedural code.
π§ Quick Revision Questions
- What are the five main highlights of WPF, and explain each briefly?
- How does WPF differ from Win32 and Windows Forms in terms of UI redesign and developer/designer collaboration?
- What new features were introduced in WPF 4.0, and how do they improve the developer experience?
- When should you choose Silverlight over WPF, and what technique is used to handle code incompatibilities between them?
- Why is XAML described as a "declarative programming language," and is it mandatory to use it in WPF projects? Explain.
π Lecture 13 β XAML Specification and Mapping Rules
π Overview: This lecture explores how XAML defines rules that map .NET namespaces, types, properties, and events into XML namespaces, elements, and attributes. It covers the fundamental relationships between XAML declarations and equivalent C# code, making it essential for understanding how WPF applications are constructed declaratively.
ποΈ Topics Covered
The lecture covers XAML object elements and their mapping to .NET objects, property and event attributes, XML namespace declarations including the XAML language namespace, property elements for rich composition, type converters for automatic string-to-object conversion, markup extensions with curly brace syntax, content properties, and collection handling including lists and dictionaries.
π Lecture Summary
XAML Object Elements and Property/Event Attributes
XAML specification defines rules that map .NET namespaces, types, properties, and events into XML namespaces, elements, and attributes. Declaring an XML element in XAML (known as an object element) is equivalent to instantiating the corresponding .NET object via a default constructor. Setting an attribute on the object element is equivalent to setting a property of the same name (called a property attribute) or hooking up an event handler of the same name (called an event attribute).
π Definition β Object Element: An XML element in XAML that represents a .NET object instantiated via its default constructor.
π Formula:
XAML: <Button xmlns="..." Content="OK"/> β C#: System.Windows.Controls.Button b = new System.Windows.Controls.Button(); b.Content = "OK";
π Example:
XAML: <Button xmlns="..." Content="OK" Click="button_Click"/>
Equivalent C#:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
b.Click += new System.Windows.RoutedEventHandler(button_Click);
b.Content = "OK";
π‘ Why this matters: XAML can no longer run standalone in the browser because event handlers are attached before properties are set, requiring code-behind.
Namespaces in XAML
Mapping to the namespace used above and other WPF namespaces is hard-coded inside the WPF assemblies. The root object element in XAML must specify at least one XML namespace that qualifies itself and any child elements. Additional XML namespaces (on the root or on children) must be given a distinct prefix.
π Example:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" β This is the XAML language namespace, which maps to types in the System.Windows.Markup namespace but also defines special directives for the XAML compiler or parser.
All of the following are mapped with http://schemas.microsoft.com/winfx/2006/xaml/presentation:
System.Windows, System.Windows.Automation, System.Windows.Controls, System.Windows.Controls.Primitives, System.Windows.Data, System.Windows.Documents, System.Windows.Forms.Integration, System.Windows.Ink, System.Windows.Input, System.Windows.Media, System.Windows.Media.Animation, System.Windows.Media.Effects, System.Windows.Media.Imaging, System.Windows.Media.Media3D, System.Windows.Media.TextFormatting, System.Windows.Navigation, System.Windows.Shapes, System.Windows.Shell
Property Elements
Property elements in XAML enable rich composition. The period distinguishes property elements from object elements. Property elements don't have attributes except x:uid for localization.
π Example β Setting a Rectangle as Button content: C#:
System.Windows.Controls.Button b = new System.Windows.Controls.Button();
System.Windows.Shapes.Rectangle r = new System.Windows.Shapes.Rectangle();
r.Width = 40;
r.Height = 40;
r.Fill = System.Windows.Media.Brushes.Black;
b.Content = r;
XAML equivalent:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button.Content>
<Rectangle Height="40" Width="40" Fill="Black"/>
</Button.Content>
</Button>
π Example β Simple properties with property element syntax:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Button.Content>OK</Button.Content>
<Button.Background>White</Button.Background>
</Button>
This is equivalent to setting Content="OK" and Background="White" as attributes.
Type Converters
WPF provides type converters for many common data types: Brush, Color, FontWeight, Point, and so on. Classes deriving from TypeConverter (BrushConverter, ColorConverter) convert from string to the corresponding types. You can also write your own type converters for custom data types.
π Definition β Type Converter: A class that converts string values to .NET objects at runtime, enabling XAML attributes to use simple string representations.
π Example β Setting Background with type converter:
<Button xmlns="..." Content="OK">
<Button.Background>
<SolidColorBrush Color="White"/>
</Button.Background>
</Button>
π Example β Without the type converter for Color:
<Button xmlns="..." Content="OK">
<Button.Background>
<SolidColorBrush>
<SolidColorBrush.Color>
<Color A="255" R="255" G="255" B="255"/>
</SolidColorBrush.Color>
</SolidColorBrush>
</Button.Background>
</Button>
Even that requires a type converter for Byte.
C# equivalent without type converter:
B.Background = (Brush)System.ComponentModel.TypeDescriptor.GetConverter(
typeof(Brush)).ConvertFromInvariantString("White");
π‘ Why this matters: Constants in strings cause problems with runtime exceptions not caught at compile time, although Visual Studio checks XAML at compile time.
Markup Extensions
Markup extensions, like type converters, enable extending the expressiveness of XAML. Both can evaluate a string attribute value at runtime and produce an appropriate object. Unlike type converters, markup extensions are invoked from XAML with explicit and consistent syntax, making them a preferred approach.
Whenever an attribute value is enclosed in curly braces {}, the XAML compiler/parser treats it as a markup extension value rather than a literal string.
π Definition β Markup Extension: A class with a default constructor used in XAML with curly brace syntax to produce objects at runtime.
π Example:
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="{x:Null}"
Height="{x:Static SystemParameters.IconHeight}"
Content="{Binding Path=Height, RelativeSource={RelativeSource Mode=Self}}"/>
This works because positional parameters have corresponding property values, and the markup extension has the real code to be executed.
π Example β Escaping curly braces for literal text:
<Button xmlns=''http://schemas.microsoft.com/winfx/2006/xaml/presentation''
Content=''{}{This is not a markup extension!}''/>
Content Properties and Collection Items
An object element can have three types of children: a value for a content property, collection items, or a value that can be type-converted to the object element. The designated property is the content property.
π Definition β Content Property: The default property of a class that receives child content when no explicit property element is specified.
π Example β Content property shorthand:
<!-- Full syntax -->
<Button xmlns="..." Content="OK"/>
<!-- Equivalent using content property -->
<Button xmlns="...">OK</Button>
π Example β Content property with complex object:
<!-- Full syntax -->
<Button xmlns="...">
<Button.Content>
<Rectangle Height="40" Width="40" Fill="Black"/>
</Button.Content>
</Button>
<!-- Equivalent using content property -->
<Button xmlns="...">
<Rectangle Height="40" Width="40" Fill="Black"/>
</Button>
There is no requirement that the content property must actually be called "Content"; classes such as ComboBox, ListBox, and TabControl use their Items property as the content property, designated with a custom attribute.
Collections: Lists and Dictionaries
XAML enables adding items to the two main types of collections that support indexing: lists and dictionaries.
π Example β ListBox with explicit collection syntax:
<ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ListBox.Items>
<ListBoxItem Content="Item 1"/>
<ListBoxItem Content="Item 2"/>
</ListBox.Items>
</ListBox>
Equivalent C#:
System.Windows.Controls.ListBox listBox = new System.Windows.Controls.ListBox();
System.Windows.Controls.ListBoxItem item1 = new System.Windows.Controls.ListBoxItem();
System.Windows.Controls.ListBoxItem item2 = new System.Windows.Controls.ListBoxItem();
item1.Content = "Item 1";
item2.Content = "Item 2";
π Example β ListBox with content property shorthand:
<ListBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<ListBoxItem Content="Item 1"/>
<ListBoxItem Content="Item 2"/>
</ListBox>
π Example β Using a dictionary (ResourceDictionary):
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Color x:Key="1" A="255" R="255" G="255" B="255"/>
<Color x:Key="2" A="0" R="0" G="0" B="0"/>
</ResourceDictionary>
Equivalent C#:
System.Windows.ResourceDictionary d = new System.Windows.ResourceDictionary();
System.Windows.Media.Color color1 = new System.Windows.Media.Color();
System.Windows.Media.Color color2 = new System.Windows.Media.Color();
color1.A = 255; color1.R = 255; color1.G = 255; color1.B = 255;
color2.A = 0; color2.R = 0; color2.G = 0; color2.B = 0;
d.Add("1", color1);
d.Add("2", color2);
β Key Takeaways
XAML maps .NET objects to XML elements where each object element instantiates a .NET class, and attributes correspond to either properties or events. Two XML namespaces are essential: the WPF namespace (http://schemas.microsoft.com/winfx/2006/xaml/presentation) for all WPF controls and the XAML language namespace (xmlns:x) for directives like x:Key and x:Null. Type converters automatically convert string attribute values to their appropriate .NET types (like "White" to a Brush), while markup extensions use curly brace syntax {} for more complex runtime object creation. Property element syntax (e.g., <Button.Content>) enables rich composition when simple attribute syntax is insufficient, and collection content properties (like Items for ListBox) allow direct child element placement without explicit property elements.
π§ Quick Revision Questions
- What is the equivalent C# code for the XAML declaration
<Button xmlns="..." Content="OK" Click="button_Click"/>? - What are the two XML namespaces typically used in WPF XAML files, and what do they map to?
- How do type converters enable setting properties like
Background="White"in XAML? - What is the syntax difference between a markup extension and a type converter in XAML?
- How does the content property work, and give an example of a class that uses a property other than "Content" as its content property?
π Lecture 14 β XAML and Procedural Code Integration
π Overview: This lecture explores advanced XAML techniques including working with non-XAML designed classes like Hashtable, understanding XAML child element processing rules, and integrating XAML with procedural code. It demonstrates how to load XAML at runtime, name elements for easy access, and compile XAML with code-behind files for building complete WPF applications.
ποΈ Topics Covered
The lecture covers representing non-XAML classes like Hashtable in XAML, the detailed rules for processing XAML child elements (IList, IDictionary, content property, type converter), mixing XAML with procedural code using XamlReader, accessing elements by name using FindName and x:Name, using property element syntax for named references, Binding markup extensions and x:Reference, and the three-step XAML compilation process with code-behind files.
π Lecture Summary
Type Converters and Abstract Classes
A type converter exists that converts string to SolidColorBrush, allowing markup like <SolidColorBrush>White</SolidColorBrush>. This works even though no designated content property exists. Similarly, <Brush>White</Brush> works even though Brush is abstract, because the type converter can convert a string to a SolidColorBrush.
π Definition β Type Converter: A mechanism that converts a string value to an object of a specific type during XAML parsing.
Representing Non-XAML Classes (Hashtable Example)
Classes not originally designed for XAML, like System.Collections.Hashtable, can still be represented. A Hashtable with entries can be written as:
<Collections:Hashtable
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<sys:Int32 x:Key="key1">7</sys:Int32>
<sys:Int32 x:Key="key2">23</sys:Int32>
</Collections:Hashtable>
π‘ Why this matters: This demonstrates how XAML can work with any .NET class, not just those specifically designed for XAML.
XAML Child Element Rules
The rules for processing child elements in XAML are evaluated in order:
- If the type implements IList: Call
IList.Addfor each child element. - If the type implements IDictionary: Call
IDictionary.Addfor each child, using thex:Keyattribute value for the key and the element for the value. (XAML2009 checks IDictionary before IList.) - If the parent supports a content property (indicated by
System.Windows.Markup.ContentPropertyAttribute) and the child's type is compatible: Treat the child as the value of that property. - If the child is plain text and a type converter exists to transform the child into the parent type (and no properties are set on the parent): Treat the child as input to the type converter and use the output as the parent object instance.
- Otherwise: Treat it as unknown content and potentially raise an error.
π Rule: XAML processes children in this order: IList β IDictionary β Content Property β Type Converter β Error
Mixing XAML and Procedural Code with XamlReader
The XamlReader class allows loading XAML at runtime:
Window window = null;
using (FileStream fs = new FileStream("mywindow.xaml", FileMode.Open, FileAccess.Read))
{
window = (Window)XamlReader.Load(fs);
}
Accessing Elements by Name
Elements can be accessed by walking children with hard-coded knowledge:
StackPanel panel = (StackPanel)window.Content;
Button okButton = (Button)panel.Children[4];
A better approach uses named elements. The x:Name attribute assigns a name:
<Button x:Name="okButton">OK</Button>
Then retrieve it using FindName:
Button okButton = (Button)window.FindName("okButton");
Classes that already have a Name property can designate it as the special name using a custom attribute.
π Definition β x:Name: A XAML directive attribute that gives an element a name, enabling access from procedural code.
Named Properties and Markup Extensions
Using the Binding markup extension for element references:
<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Label Target="{Binding ElementName=box}" Content="Enter _text:"/>
<TextBox Name="box"/>
</StackPanel>
This gives focus to the TextBox when the Label's access key is pressed.
WPF 4 includes a simpler x:Reference markup extension that works at parse time:
<StackPanel ...>
<Label Target="{x:Reference box}" Content="Enter _text:"/>
<TextBox Name="box"/>
</StackPanel>
If a property is marked with the System.Windows.Markup.NameReferenceConverter type converter, a simpler syntax works:
<StackPanel ...>
<Label Target="box" Content="Enter _text:"/>
<TextBox Name="box"/>
</StackPanel>
Compiling XAML
Compiling XAML involves three steps:
- Converting a XAML file into a special binary format (BAML)
- Embedding the converted content as a binary resource in the assembly being built
- Performing plumbing that connects XAML with procedural code automatically
The first step involves specifying a subclass for the root element using the x:Class keyword:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MyNamespace.MyWindow">
</Window>
This is paired with a code-behind file:
namespace MyNamespace
{
partial class MyWindow : Window
{
public MyWindow()
{
// Necessary to call in order to load XAML-defined content!
InitializeComponent();
}
// Any other members can go here...
}
}
The partial keyword is important for combining the XAML-generated class with the code-behind class. Event handlers are typically defined in the code-behind file.
π Definition β Code-Behind: A partial class file that contains procedural code (event handlers, business logic) paired with a XAML file, together forming a complete class.
β Key Takeaways
XAML can represent non-XAML designed classes like Hashtable using appropriate namespace declarations and the x:Key attribute for dictionary entries. The child element processing rules follow a strict priority: IList first, then IDictionary, then content property, then type converter, and finally error. Elements can be named with x:Name and retrieved from procedural code using FindName, eliminating the need for fragile hard-coded child indices. XAML compilation converts markup to BAML binary format, embeds it as a resource, and automatically connects it with code-behind partial classes using x:Class. The Binding markup extension and the newer x:Reference markup extension both enable element references, but x:Reference works at parse time and is simpler.
π§ Quick Revision Questions
- What is the order of priority for XAML child element processing rules?
- How would you represent a Hashtable with three string-integer pairs in XAML?
- What are the three steps involved in compiling XAML?
- How do you access a named button, declared with
x:Name="submitButton", from procedural code? - Why is the
partialkeyword important in a code-behind file?
π Lecture 15 β BAML, XAML Features, and WPF Fundamentals
π Overview: This lecture covers BAML (Binary Application Markup Language) as a compressed representation of XAML, explores XAML 2009 and 2006 keywords and markup extensions, and introduces the fundamental WPF class hierarchy including DependencyObject, Visual, UIElement, and FrameworkElement. It also explains the difference between logical and visual trees and how to traverse them programmatically.
ποΈ Topics Covered
The lecture begins with BAML and its relationship to XAML, including loading mechanisms and conversion back to XAML. It then discusses XAML 2009 features and XAML 2006 keywords, followed by markup extensions. The second half introduces WPF fundamentals through its deep inheritance hierarchy, covering key classes from DispatcherObject to Control. Finally, the lecture explains logical versus visual trees and provides code examples for traversing both trees using helper classes.
π Lecture Summary
BAML and XAML Loading
BAML (Binary Application Markup Language) is a compressed representation of XAML. There is a BAML reader available. Earlier there was CAML (Compiled Application Markup Language) but it is no longer used. When using x:Class, some glue code is generated, similar to loading and parsing the XAML file. You must call InitializeComponent() and can refer to named elements like class members.
Procedural code can be written inside the XAML file using <x:Code> with CDATA sections. However, you must avoid ]] inside the code; if needed, use entities like < and &. There is no good reason to embed code in XAML, as internally the build system compiles it into a .cs file.
BAML can be converted back to XAML:
System.Uri uri = new System.Uri("/wpfapplication1;component/mywindow.xaml", System.urikind.Relative);
Window window = (Window)Application.LoadComponent(uri);
String xaml = XamlWriter.Save(window);
There are different loading mechanisms: from a resource identified by the original XAML file, or from the integrated BAML that is loaded.
π Definition β BAML: Binary Application Markup Language β a compressed binary representation of XAML that improves load performance.
XAML 2009 and 2006 Features
Key features of XAML 2009 include: full generics support using typearguments, dictionary keys of any type, built-in system data types, creating objects with non-default constructors, getting instances via factory methods, event handlers can be markup extensions returning delegates, and defining additional members and properties. The System.Xaml.XamlXmlReader class can be extended with readers and writers for many formats. It abstracts differences in XAML formats like accessing a content property, property element, or property attribute.
XAML 2006 keywords include:
x:AsyncRecordsβ controls the size of asynchronous XAML-loading chunksx:Classβ specifies the code-behind classx:ClassModifierβ visibility (public by default)x:Codeβ inline codex:ConnectionIdβ not for public usex:FieldModifierβ field visibility (internal by default)x:Keyβ resource dictionary keyx:Nameβ element namex:Sharedβ=falsemeans same resource instance not sharedx:Subclassβ only needed when partial classes not supportedx:SynchronousModeβ XAML loaded in async modex:TypeArgumentsβ used only with root withx:Classin XAML 2006x:Uidβ representsSystem.Urix:XDataβ data opaque for XAML parser
Markup extensions often confused with keywords include:
x:Arrayβ use withx:Typeto define type of arrayx:Nullβ null valuex:Referenceβ reference to named elementx:Staticβ static property/fieldx:Typeβ like thetypeofoperator
π‘ Why this matters: Understanding these keywords and markup extensions is essential for proper XAML authoring and for reading/writing XAML programmatically.
WPF Class Hierarchy
WPF concepts are above and beyond .NET concepts, causing the steep learning curve of WPF. It has a deep inheritance hierarchy with a handful of fundamental classes.
Key classes in the hierarchy (from base to derived):
π Definition β DispatcherObject: The base class for any object that wishes to be accessed only on the thread that created it. Most WPF classes derive from DispatcherObject and are inherently thread-unsafe.
π Definition β DependencyObject: The base class for any object that can support dependency properties.
π Definition β Freezable: The base class for objects that can be "frozen" into a read-only state for performance reasons. Freezables, once frozen, can be safely shared among multiple threads, unlike DispatcherObjects. Frozen objects can never be unfrozen, but you can clone them.
π Definition β Visual: The base class for all objects that have their own 2D visual representation.
π Definition β UIElement: The base class for all 2D visual objects with support for routed events, command binding, layout, and focus.
π Definition β Visual3D: The base class for all objects that have their own 3D visual representation.
π Definition β UIElement3D: The base class for all 3D visual objects with support for routed events, command binding, and focus.
π Definition β ContentElement: A base class similar to UIElement but for document-related pieces of content that don't have rendering behavior on their own. Instead, ContentElements are hosted in a Visual-derived class to be rendered on screen.
π Definition β FrameworkElement: The base class that adds support for styles, data binding, resources, tooltips, and context menus.
π Definition β FrameworkContentElement: The analog to FrameworkElement for content.
π Definition β Control: The base class for familiar controls such as Button, ListBox, and StatusBar. Control adds properties like Foreground, Background, and FontSize, as well as the ability to be completely restyled.
Logical and Visual Trees
XAML is good for UI because of its hierarchical nature. A logical tree exists even without XAML. Properties, events, and resources are tied to logical trees. Properties are propagated down and events can be routed up or down the tree. It is a simplification of what actually happens during rendering.
The visual tree can be thought of as an extension of the logical tree, though some things can be dropped as well. The visual tree exposes visual implementation details β for example, a ListBox is actually a Border, two ScrollBars, and more. Only things from Visual or Visual3D appear in a visual tree. You should avoid depending on the visual tree in your code.
You can traverse trees using System.Windows.LogicalTreeHelper and System.Windows.Media.VisualTreeHelper.
The visual tree is empty until the dialog box is rendered. Navigating either tree can be done in instance methods of the elements themselves β for example, the Visual class has protected members VisualParent, VisualChildrenCount, and GetVisualChild. FrameworkElement and FrameworkContentElement have a Parent property and a LogicalChildren property.
π Example: A code-behind file that prints both logical and visual trees:
void PrintLogicalTree(int depth, object obj)
{
Debug.WriteLine(new string(' ', depth) + obj);
if (!(obj is DependencyObject))
return;
foreach (object child in LogicalTreeHelper.GetChildren(obj as DependencyObject))
PrintLogicalTree(depth + 1, child);
}
void PrintVisualTree(int depth, DependencyObject obj)
{
Debug.WriteLine(new string(' ', depth) + obj);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
PrintVisualTree(depth + 1, VisualTreeHelper.GetChild(obj, i));
}
This code recursively traverses the logical tree using LogicalTreeHelper.GetChildren and the visual tree using VisualTreeHelper.GetChildrenCount and GetChild.
β Key Takeaways
- BAML is a compressed binary form of XAML that improves performance; it can be converted back to XAML using
Application.LoadComponentandXamlWriter.Save. - XAML provides both keywords (like
x:Class,x:Name,x:Key) and markup extensions (likex:Static,x:Type,x:Null) that serve different purposes and are essential for WPF development. - The WPF class hierarchy is deep and fundamental β starting from Object β DispatcherObject β DependencyObject β Freezable β Visual β UIElement β FrameworkElement β Control β understanding this hierarchy explains thread safety, dependency properties, freezing, and visual rendering behavior.
- Logical trees represent the simplified UI structure for property/event propagation, while visual trees expose the actual rendering details; use
LogicalTreeHelperandVisualTreeHelperfor traversal, but avoid depending on visual tree structure in code. - The visual tree is only populated after rendering occurs, and most WPF objects are thread-unsafe due to their DispatcherObject inheritance.
π§ Quick Revision Questions
- What is the difference between BAML and XAML?
- List three XAML 2009 features that are not available in XAML 2006.
- What is the difference between
x:Nameandx:Keyin XAML? - Why are most WPF objects inherently thread-unsafe, and which class allows safe multi-threaded sharing when frozen?
- How does the logical tree differ from the visual tree, and which helper classes are used to traverse each?
π Lecture 16 β Dependency Properties and Attached Properties
π Overview: This lecture introduces dependency properties, a fundamental WPF infrastructure that extends standard .NET properties with features like change notification, property value inheritance, and support for multiple value providers. Understanding dependency properties is essential for working with WPF because only dependency properties can be styled and animated.
ποΈ Topics Covered
This lecture covers the motivation and implementation of dependency properties, the standard pattern for registering them with static fields and property wrappers, their benefits including per-instance memory savings and change notification, property triggers in XAML, property value inheritance across element trees, the five-step process for determining property values with precedence rules, and attached properties as a special type of dependency property.
π Lecture Summary
Dependency Properties: Motivation and Implementation
Dependency properties depend on multiple providers for determining their value at any point in time. Providers can include animations, parent properties propagating down, and more. The biggest feature is change notification. Motivation is to add rich functionality from declarative markup without procedural code. For example, Button has 111 public properties (98 inherited), and setting these from XAML or a design tool would be hard without dependency properties. Key features include change notification, property value inheritance, and support for multiple providers. Only dependency properties can be styled and animated. In practice, dependency properties are normal .NET properties with extra WPF infrastructure.
π Definition β Dependency Property: A property whose value depends on multiple providers (animations, parent elements, styles, etc.) and is represented by System.Windows.DependencyProperty.
π Example: Standard dependency property implementation for Button:
public class Button : ButtonBase
{
// The dependency property
public static readonly DependencyProperty IsDefaultProperty;
static Button()
{
// Register the property
Button.IsDefaultProperty = DependencyProperty.Register("IsDefault", typeof(bool), typeof(Button));
}
// A .NET property wrapper (optional)
public bool IsDefault
{
get { return (bool)GetValue(Button.IsDefaultProperty); }
set { SetValue(Button.IsDefaultProperty, value); }
}
// A property changed callback (optional)
private static void OnIsDefaultChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
//...
}
}
Dependency properties are represented by System.Windows.DependencyProperty. By convention, they are public static with the Property suffix. This is required by localization tools, XAML loading, etc. Optionally, metadata can be passed via overloads of Register to customize how the property is treated by WPF, and callbacks for handling property value changes, coercing values, and validating values. The .NET property wrapper is optional but helps with setting from XAML; otherwise, GetValue and SetValue methods inherited from System.Windows.DependencyObject must be used. GetValue and SetValue do not support generics because dependency properties were introduced before generic support in C#. Visual Studio has a snippet called propdp that automatically expands into a dependency property definition. .NET property wrappers are bypassed at runtime when setting dependency properties in XAMLβWPF calls GetValue and SetValue directly. Therefore, property wrappers should not contain any logic beyond these calls; custom logic should use registered callbacks.
π‘ Why this matters: Although the code seems verbose, dependency properties save per-instance cost by using only a static field and an efficient sparse storage system. If all Button properties were .NET properties with backing store, they would consume much more space (e.g., 111 fields for Button, but 89 are dependency properties). Additionally, code for thread access checking and re-rendering is handled automatically.
Change Notification via Property Triggers
Dependency properties support change notification based on metadata at register time. Actions can include re-rendering elements, updating layout, refreshing data bindings, and firing property triggers. For example, you can change color on hovering.
With procedural code:
void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null) b.Foreground = Brushes.Blue;
}
void Button_MouseLeave(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null) b.Foreground = Brushes.Black;
}
And with XAML triggers:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Blue"/>
</Trigger>
Triggers cannot be applied directly to Button elements. They must be wrapped in a Style:
<Button MinWidth="75" Margin="10">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Property Value Inheritance
Property value inheritance is the flowing of property values down an element tree. For example:
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">WPF 4 Unleashed</Label>
<Label>2010 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button MinWidth="75" Margin="10">Help</Button>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
</StackPanel>
Inheritance does not affect the StatusBar because not every dependency property participates in inheritance (they must opt-in). Some controls like StatusBar internally set their values to system defaults. Property value inheritance also applies to triggers inside a definition.
Value Determination: Five-Step Process
WPF has many mechanisms that independently attempt to set the value of dependency properties. Dependency properties are designed to depend on these providers in a consistent and orderly manner. The process has five steps:
Step 1: Determine base value β Ten providers set the value with a specific precedence (highest to lowest):
- Local value (
DependencyObject.SetValue, property assignment in XAML) - Parent template trigger
- Parent template
- Style triggers
- Template triggers
- Style setters
- Theme style triggers
- Theme style setters
- Property value inheritance
- Default value (initial value registered with the property)
This explains why the StatusBar did not get font propagated. Use DependencyPropertyHelper.GetValueSource to find which source was used.
Step 2: Evaluate β Expressions (e.g., data binding) need evaluation.
Step 3: Apply animation β Animations can alter the value from Step 2 or replace it.
Step 4: Coerce β The almost-final value is passed to the CoerceValueCallback delegate if one is registered.
Step 5: Validate β The value is passed to the ValidateValueCallback delegate. Returning false causes an exception canceling the entire process. WPF 4 adds SetCurrentValue in DependencyObject, which updates the current value without changing the value source.
Attached Properties
Attached properties are special dependency properties that can be attached to arbitrary objects. They have a special XAML syntax.
Example:
<StackPanel TextElement.FontSize="30" TextElement.FontStyle="Italic" Orientation="Horizontal">
<Button MinWidth="75" Margin="10">Help</Button>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
Here, TextElement.FontSize and TextElement.FontStyle are attached properties that affect child elements without those properties being defined on StackPanel itself.
β Key Takeaways
The key takeaways from this lecture are that dependency properties extend standard .NET properties with WPF-specific infrastructure including change notification, property value inheritance across element trees, and a five-step value determination process with ten precedence levels. Only dependency properties can be styled and animated in WPF. The implementation pattern involves a public static readonly field, registration via DependencyProperty.Register, and an optional property wrapper that must only call GetValue/SetValue without additional logic. Property triggers enable declarative behavior changes without procedural code. Attached properties are dependency properties that can be applied to any object, enabling cross-type property setting (like TextElement.FontSize on a StackPanel). Memory efficiency is achieved because dependency properties use static fields and sparse storage instead of per-instance backing fields.
π§ Quick Revision Questions
- What are the three key features of dependency properties that motivate their use over standard .NET properties?
- Why must .NET property wrappers for dependency properties contain no logic other than
GetValue/SetValuecalls? - List the ten providers that determine the base value of a dependency property in order of precedence.
- Why did the StatusBar in the property value inheritance example not inherit the font settings from the parent StackPanel?
- What is the difference between a dependency property and an attached property?