WPF (.NET Framework)

Welcome to the official documentation for Windows Presentation Foundation (WPF) within the .NET Framework. WPF is a powerful UI framework for building Windows desktop applications with rich user interfaces, declarative UI markup (XAML), data binding, styles, templates, and much more.

Introduction to WPF

WPF enables you to create visually stunning and responsive user interfaces. It separates the UI design from the application logic, promoting a cleaner architecture and facilitating collaboration between designers and developers. Key features include:

Getting Started

To begin developing WPF applications, you'll need Visual Studio with the .NET desktop development workload installed. You can create a new WPF project from the Visual Studio start window.

Creating a New WPF Project

  1. Open Visual Studio.
  2. Click "Create a new project".
  3. Search for "WPF App (.NET Framework)".
  4. Select the template and click "Next".
  5. Configure your project name and location, then click "Create".

This will create a basic WPF application with a main window defined in XAML and code-behind.

UI Elements

WPF provides a vast collection of built-in UI elements (controls) for creating your interfaces. These range from basic controls like Buttons and TextBoxes to more complex ones like DataGrids and TreeViews.

You can arrange these elements using layout panels.

Layout System

The WPF layout system is highly flexible, allowing you to create complex and adaptive UIs. Elements are measured and arranged by their parent containers. Common layout panels include:

StackPanel

Arranges child elements in a single line, either horizontally or vertically.

<StackPanel Orientation="Horizontal">
    <Button Content="Button 1" />
    <Button Content="Button 2" />
</StackPanel>

Grid

Arranges child elements in a table-like structure of rows and columns. It's very powerful for creating complex layouts.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="Header" Grid.Row="0" Grid.Column="0" />
    <TextBlock Text="Content" Grid.Row="1" Grid.Column="1" />
</Grid>

DockPanel

Arranges child elements by "docking" them to the top, bottom, left, or right edges of the available space.

<DockPanel>
    <Border Background="LightGray" DockPanel.Dock="Top" Height="50" />
    <Border Background="Gray" DockPanel.Dock="Bottom" Height="50" />
    <Border Background="DarkGray" />
</DockPanel>

Canvas

Provides an un-scrolled, fixed-size surface where child elements can be positioned using absolute coordinates.

<Canvas Background="LightBlue">
    <Rectangle Fill="Red" Width="50" Height="50" Canvas.Left="10" Canvas.Top="10" />
    <Ellipse Fill="Yellow" Width="40" Height="40" Canvas.Left="70" Canvas.Top="30" />
</Canvas>

WrapPanel

Arranges child elements in a line until the line is full, then wraps to the next line.

<WrapPanel>
    <Button Content="Button 1" Margin="5"/>
    <Button Content="Button 2" Margin="5"/>
    <Button Content="Button 3" Margin="5"/>
    <Button Content="Button 4" Margin="5"/>
</WrapPanel>

XAML Overview

XAML (Extensible Application Markup Language) is an XML-based language used to define the user interface of a WPF application. It allows you to:

XAML is compiled into intermediate language (IL) during the build process, which is then executed by the WPF runtime.

Basic Window in XAML

<Window x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="My WPF App" Height="350" Width="525">
    <Grid>
        <Button Content="Click Me" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</Window>

Data Binding

Data binding is a fundamental feature of WPF that allows you to synchronize data between UI elements and data sources (e.g., business objects, collections). This greatly simplifies the process of displaying and updating data.

Key concepts include:

<!-- Binding a TextBox's Text property to a property named 'UserName' on its DataContext -->
<TextBox Text="{Binding UserName, UpdateSourceTrigger=PropertyChanged}" />

Styles and Templates

Styles allow you to define reusable sets of properties that can be applied to multiple elements to control their appearance.

Control Templates enable you to redefine the visual structure and appearance of a control without changing its behavior.

Custom Button Style

<Window.Resources>
    <Style TargetType="Button" x:Key="MyButtonStyle">
        <Setter Property="Background" Value="CornflowerBlue"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="Padding" Value="10,5"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="Black"
                            BorderThickness="1"
                            CornerRadius="5"
                            Padding="{TemplateBinding Padding}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

<Button Content="Styled Button" Style="{StaticResource MyButtonStyle}" />

Commands

Commands provide a way to encapsulate actions and decouple the UI from the execution logic. They are often used with data binding, especially for input gestures like button clicks or menu item selections.

The ICommand interface and built-in commands like Click and InvokeCommandAction are key components.

Resource Management

WPF's resource system allows you to define and access resources like styles, templates, brushes, and string values efficiently. Resources can be defined at various levels (e.g., Window, Application) and accessed using StaticResource or DynamicResource.

Animation

WPF provides a powerful animation system that allows you to create smooth visual effects and transitions. You can animate properties of UI elements, including position, size, color, opacity, and more.

Event Handling

WPF uses a routed events system, which allows events to travel up or down the element tree. This enables more flexible event handling strategies, such as event bubbling and tunneling.

// Example: Handling a Button's Click event in C# code-behind
private void MyButton_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Button was clicked!");
}