WPF Fundamentals

Introduction

Windows Presentation Foundation (WPF) is a UI framework for building rich Windows desktop applications. Introduced in .NET Framework 3.0, it combines declarative UI with powerful graphics, layout, and data binding capabilities.

WPF Architecture

WPF is built on three core layers:

  • PresentationFramework: High‑level UI elements and controls.
  • PresentationCore: Low‑level rendering, media, and input.
  • WindowsBase: Core services such as threading and resources.

All layers rely on the DirectX rendering pipeline, enabling hardware acceleration.

XAML Basics

XAML (Extensible Application Markup Language) defines UI declaratively. Example:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="Hello, WPF" Height="300" Width="400">
    <Grid>
        <TextBlock Text="Welcome to WPF!" 
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   FontSize="24"/>
    </Grid>
</Window>

Code‑behind files (.cs) handle events and logic, linked via x:Class.

Layout System

WPF provides flexible panels to arrange child elements:

  • StackPanel – one‑dimensional stacking.
  • Grid – two‑dimensional table layout.
  • DockPanel – docking to edges.
  • WrapPanel – flow layout.

Each panel participates in a two‑phase layout pass: measure and arrange.

Core Controls

Common controls include:

ControlDescription
ButtonClickable UI element.
TextBoxEditable text input.
ListBoxDisplays a list of selectable items.
ComboBoxDrop‑down selection.
DataGridTabular data display.

Data Binding

Binding connects UI elements to data sources, using {Binding} markup extensions.

<TextBox Text="{Binding Path=UserName, Mode=TwoWay}" />

Supported sources include objects, collections, XML, and dependency properties. Use INotifyPropertyChanged for update notifications.

Resources & Styles

Define reusable resources (brushes, templates, styles) at the application, window, or control level.

<Window.Resources>
    <SolidColorBrush x:Key="AccentBrush" Color="#FF0066B8"/>
    <Style TargetType="Button">
        <Setter Property="Background" Value="{StaticResource AccentBrush}"/>
        <Setter Property="Foreground" Value="White"/>
    </Style>
</Window.Resources>

Routed Events

Routed events travel through the visual tree, enabling parent controls to react to child actions.

private void Button_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Button clicked!");
}

Use Click="Button_Click" in XAML to attach.

Performance Tips

  • Prefer VirtualizingStackPanel for large lists.
  • Use BitmapCache for static visuals.
  • Limit the use of Opacity and Effect on large surfaces.
  • Profile with the Visual Studio Diagnostic Tools.