Skip to content
Tutorials Center
My learning

Topics

Lesson 168 of 182 ยท Advanced C#

Desktop and Mobile UI: WPF, WinForms, MAUI

Compare the C# UI frameworks - WinForms, WPF, WinUI, .NET MAUI, Avalonia and Blazor Hybrid - and learn the shared ideas (UI thread, layout, XAML, binding) with runnable simulations and read-only samples.

C# is not only a language for servers and websites. It is also one of the most common ways to build programs that have windows, buttons and touch screens: accounting software, hospital systems, trading terminals, point-of-sale tablets, design tools and mobile apps. Microsoft and the community offer several UI frameworks for it, and the list can look confusing at first: WinForms, WPF, WinUI, UWP, Xamarin, MAUI, Avalonia, Uno, Blazor Hybrid. Which one do you pick, and what do they have in common?

This lesson is an overview. Real WPF and MAUI programs need a graphics system and a platform SDK, so they cannot run in our in-browser editor and their code is shown read-only. But the ideas behind all of them are plain C#, and we can run those: the UI thread and why await is so important in UI code, and the two-pass layout every XAML framework performs. The previous lessons Games and Desktop Apps and INotifyPropertyChanged and MVVM covered the game loop and data binding; here you get the map of the territory.

The framework family tree

flowchart TD
    A["Win32 / GDI"] --> B["WinForms<br/>2002, event handlers, designer"]
    A --> C["WPF<br/>2006, XAML, data binding, GPU rendering"]
    C --> D["UWP / WinUI 3<br/>modern Windows UI"]
    C --> E["Silverlight (retired)"]
    F["Xamarin.Forms<br/>(support ended 2024)"] --> G[".NET MAUI<br/>Android, iOS, macOS, Windows"]
    C -. "same ideas" .-> H["Avalonia, Uno Platform<br/>community cross-platform"]
    I["ASP.NET Core Blazor"] --> J["Blazor Hybrid<br/>web UI in a native shell"]

Most of today's frameworks descend from the XAML-and-binding ideas introduced by WPF; WinForms is the older, simpler event-handler model.

Framework Platforms UI described with Best for
Windows Forms (WinForms) Windows Designer-generated C# code, event handlers Quick internal tools and maintaining the many existing apps
WPF Windows XAML markup + C#, data binding, templates, styles Rich Windows desktop applications, business software
WinUI 3 (Windows App SDK) Windows 10/11 XAML (modern controls, Fluent design) New Windows-only apps that want the current look
.NET MAUI Android, iOS, macOS (Mac Catalyst), Windows XAML or C# markup One codebase for phones, tablets and desktop
Avalonia Windows, macOS, Linux, mobile, WebAssembly XAML dialect, own rendering engine Cross-platform desktop including Linux
Uno Platform Windows, macOS, Linux, mobile, WebAssembly WinUI-style XAML Reusing WinUI skills and code everywhere
Blazor Hybrid Same as MAUI/WPF/WinForms hosts HTML/CSS with Razor components in a web view Teams that already build web UIs

A few facts that help you choose:

  • WinForms and WPF run on modern .NET (not just the old .NET Framework). Both are Windows-only, ship with the .NET SDK's Windows desktop workload, and are actively maintained, though mostly for compatibility and polish rather than big new features.
  • Xamarin.Forms reached end of support in May 2024. .NET MAUI is its successor: one single project that targets several platforms, with platform code in per-platform folders.
  • Building for iOS requires a Mac (the build uses Apple's toolchain), even though you write C#. Android and Windows can be built anywhere the SDKs install.
  • There is no first-party Linux desktop framework. Avalonia and Uno fill that gap.
  • For games, use an engine instead (Unity, Godot, MonoGame): see Games and Desktop Apps.

What every UI framework has in common

Whatever the name on the box, UI programs share the same skeleton:

  1. One UI thread. All controls belong to a single thread that runs an event loop: wait for a message (click, key, timer, repaint), handle it, wait again. Controls may only be touched from that thread.
  2. A tree of elements. The window contains panels, which contain controls. Each element has a size and a position computed by a layout pass.
  3. Events and commands. User actions arrive as events (Click, TextChanged) or are bound to ICommands.
  4. A way to keep the UI and the data in sync: manual updates in WinForms, data binding with INotifyPropertyChanged in XAML frameworks.
  5. Resources, styles and templates so the look can change without touching logic.
  6. Packaging: installers (MSIX, ClickOnce, MSI) for Windows, app-store packages for mobile.
sequenceDiagram
    participant OS as Operating system
    participant Loop as UI event loop (UI thread)
    participant App as Your handlers
    OS->>Loop: Button clicked
    Loop->>App: Click event
    App->>App: update state / start async work
    App-->>Loop: return quickly
    OS->>Loop: Repaint requested
    Loop->>Loop: layout + draw
    Note over Loop,App: A handler that blocks freezes the whole window

The loop handles one message at a time; if your handler is slow, painting and clicking wait.

The UI thread and await

Because the UI thread handles painting as well as clicks, a button handler that does five seconds of work makes the window "Not Responding". The fix is to start slow work asynchronously and let the UI thread keep pumping messages. The beautiful part of C# is that async/await makes this look like straight-line code: the code after an await automatically resumes on the UI thread, because UI frameworks install a SynchronizationContext that await captures (see async/await and tasks). Work you push to the thread pool with Task.Run runs on a different thread, where touching controls is forbidden.

The simulation below builds a miniature UI thread: a queue of messages processed by one dedicated thread, a SynchronizationContext that posts continuations to it, and a label that refuses access from any other thread, just as real controls do. Watch which thread runs each line.

C# A miniature UI thread with a SynchronizationContext

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the first block: the handler started on UI, the heavy lambda ran on a thread-pool thread (it prints a worker name, not UI), and the line after await printed UI again. That is the whole trick behind responsive UIs. The second scenario is the error message real WPF and WinForms users see when they update a control from a Task.Run lambda or a timer thread. The third shows why ConfigureAwait(false) is advice for library code, which should not care about the caller's thread, and a trap in UI event handlers, where you want to come back to the UI thread. Frameworks give you a safe way back from other threads: Dispatcher.Invoke / Dispatcher.BeginInvoke in WPF, Control.Invoke in WinForms, MainThread.BeginInvokeOnMainThread in MAUI.

Never block the UI thread by waiting on a task (task.Result, task.Wait(), GetAwaiter().GetResult()). The continuation of that task wants to run on the UI thread, which is busy waiting for it, and the program deadlocks. Use await all the way up from the event handler (async void is acceptable only for event handlers).

Layout: measure, then arrange

XAML frameworks do not position controls with fixed coordinates (though you can). Instead, every element takes part in a two-pass layout:

  1. Measure: the parent asks each child "how big would you like to be, if I could give you up to this much space?" Each child answers with a desired size, after asking its own children.
  2. Arrange: the parent now knows all desired sizes, decides the final rectangle for each child, and tells it "you live here". Children arrange their own children inside.
flowchart TD
    W["Window"] -->|"Measure(available)"| S["StackPanel (vertical)"]
    S -->|"Measure"| L["Label"]
    S -->|"Measure"| B["Button"]
    S -->|"Measure"| H["StackPanel (horizontal)"]
    L -->|"desired size"| S
    B -->|"desired size"| S
    H -->|"desired size"| S
    S -->|"desired size"| W
    W -->|"Arrange(final rect)"| S

Measure flows down with the space on offer and desired sizes flow back up; then Arrange flows down with final rectangles.

This is why windows resize gracefully, why a localized label ("Speichern" instead of "Save") pushes its neighbor over instead of overlapping, and why layout panels (StackPanel, Grid, DockPanel, WrapPanel, FlexLayout in MAUI) exist. The next program implements the algorithm for a vertical and a horizontal stack panel:

C# Measure and arrange, the XAML layout algorithm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The root's desired width is the widest child (Create account, 14 characters, 128 pixels) plus padding, and its desired height is the sum of the rows. The button row is itself a panel whose desired width is the sum of its two buttons. In the arrange pass the vertical panel stretches every row to its own width (that is what HorizontalAlignment="Stretch" does by default in XAML), while the horizontal panel gives each button exactly its desired width. With longer German captions, the buttons take more room automatically. Real frameworks add many more rules (margins, minimum and maximum sizes, star-sized Grid columns, scroll viewers, clipping, layout rounding), but this loop is the core.

XAML: markup for the element tree

XAML is an XML dialect for creating .NET objects. The tag <Button> creates a Button, an attribute sets a property, and curly braces are markup extensions such as and . A WPF window with a view-model binding (read-only; see Games and Desktop Apps for the view-model class):

XML
<!-- Read-only: MainWindow.xaml in a WPF project -->
<Window x:Class="Shop.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Products" Height="320" Width="480">
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Margin" Value="4"/>
            <Setter Property="Padding" Value="12,4"/>
        </Style>
    </Window.Resources>

    <DockPanel Margin="12">
        <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Content="Add" Command="{Binding AddCommand}"/>
            <Button Content="Remove" Command="{Binding RemoveCommand}"/>
        </StackPanel>

        <ListBox ItemsSource="{Binding Products}" SelectedItem="{Binding Selected}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}" Width="200"/>
                        <TextBlock Text="{Binding Price, StringFormat=C}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DockPanel>
</Window>

Everything here maps to ideas you already know: DockPanel and StackPanel are the layout panels, Command="{Binding AddCommand}" binds to an ICommand, ItemsSource binds to an ObservableCollection<Product>, and the DataTemplate says how to draw one item. The Style in the resources is applied to every Button in the window. Because the UI is data, tools can offer a live designer, hot reload (edit the XAML while the app runs), and designers and developers can work in parallel.

A project file declares the target. WPF needs a Windows-specific target framework:

XML
<!-- Read-only: Shop.csproj for WPF (WinForms uses UseWindowsForms instead) -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net10.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>
Terminal
# Read-only: create and run on your own Windows machine
dotnet new wpf -n Shop
cd Shop
dotnet run

WinForms in one screen

WinForms is the simplest model and still common. The designer writes code that creates controls and wires events; you fill in handlers. There is no data-binding contract to learn first, and no markup. The price is that you keep the UI and the data in sync by hand, and layouts are mostly pixel positions or anchors (which makes high-DPI and localization harder than in XAML).

C#
// Read-only: a WinForms form written by hand
var name = new TextBox { Left = 12, Top = 12, Width = 200 };
var greet = new Button { Text = "Greet", Left = 12, Top = 44 };
var output = new Label { Left = 12, Top = 80, Width = 300 };

greet.Click += (sender, e) => output.Text = $"Hello, {name.Text}!";

Application.Run(new Form { Text = "Hello", Controls = { name, greet, output } });

.NET MAUI: one project, many platforms

A MAUI app is one project that builds for Android, iOS, macOS (through Mac Catalyst) and Windows. Pages use XAML (or C# markup) with controls like Label, Button, CollectionView, and layouts like VerticalStackLayout, Grid and FlexLayout. Under the hood, each MAUI control is a thin wrapper over a native control, connected by a handler: a MAUI Button becomes an Android MaterialButton, an iOS UIButton or a WinUI Button, so the app looks native and gets platform accessibility for free. When you need platform-specific behavior, you write it in Platforms/Android, Platforms/iOS folders or with conditional compilation (#if ANDROID).

XML
<!-- Read-only: MainPage.xaml in a MAUI project -->
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Shop.MainPage" Title="Products">
    <VerticalStackLayout Padding="16" Spacing="12">
        <SearchBar Text="{Binding Query}" Placeholder="Search products"/>
        <CollectionView ItemsSource="{Binding Products}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <HorizontalStackLayout Spacing="8">
                        <Label Text="{Binding Name}" FontAttributes="Bold"/>
                        <Label Text="{Binding Price, StringFormat='{0:C}'}"/>
                    </HorizontalStackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        <Button Text="Add to cart" Command="{Binding AddCommand}"/>
    </VerticalStackLayout>
</ContentPage>
C#
// Read-only: MauiProgram.cs, the app's entry point with dependency injection
public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder.UseMauiApp<App>();
        builder.Services.AddSingleton<IProductService, ProductService>();
        builder.Services.AddTransient<MainViewModel>();
        builder.Services.AddTransient<MainPage>();
        return builder.Build();
    }
}

MAUI uses the same dependency injection container and the same MVVM patterns as the rest of this tutorial, and ships device APIs through Microsoft.Maui.* namespaces (connectivity, geolocation, preferences, secure storage, file picker). Its navigation system, Shell, gives you tabs, flyouts and URL-style routes (Shell.Current.GoToAsync("details?id=7")). You install the workload once (dotnet workload install maui) and create a project with dotnet new maui. Be realistic about the cost: the toolchains (Android SDK, Xcode) are large, builds are slower than server apps, and control behavior can differ slightly between platforms, so test on real devices.

Blazor Hybrid and web-first options

If your team's strength is web UI, Blazor Hybrid hosts Razor components inside a native window using a web view, in MAUI, WPF or WinForms. The UI is HTML and CSS, but your C# runs in-process (no server, no WebAssembly download) and can call native APIs directly. Another web-first option is a progressive web app: the same Blazor or JavaScript site, installable from the browser. The trade-off is less native feel and weaker access to device features.

Choosing a framework

flowchart TD
    Q["What are you building?"] --> W{"Windows only?"}
    W -- yes --> D{"New app or existing?"}
    D -- "existing WinForms/WPF" --> E["Stay, modernize gradually"]
    D -- "new, rich UI" --> F["WPF or WinUI 3"]
    D -- "new, simple internal tool" --> G["WinForms"]
    W -- no --> M{"Need mobile?"}
    M -- yes --> H[".NET MAUI<br/>(or Blazor Hybrid)"]
    M -- "desktop incl. Linux" --> I["Avalonia or Uno"]
    M -- "mostly web skills" --> J["Blazor Hybrid or a PWA"]

Start from the platforms you must reach, then from the skills your team already has.

Whatever you pick, a few habits pay off in every framework:

  • Keep logic out of the view. Put rules and state in plain classes and view-models you can unit test; keep code-behind for purely visual work.
  • Never block the UI thread, and marshal back to it from other threads.
  • Virtualize long lists (VirtualizingStackPanel in WPF, CollectionView in MAUI): only visible rows are created.
  • Design for localization and accessibility from the start (see localization): flexible layouts, automation names, keyboard navigation, scalable fonts, high contrast.
  • Dispose and unsubscribe from events on long-lived objects to avoid leaks.
  • Test the UI at the edges: view-model unit tests first, then a few end-to-end UI automation checks (WinAppDriver/Appium, Microsoft.Maui.Controls test helpers).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does updating a control from inside Task.Run throw an exception in WPF or WinForms?

    UI controls have thread affinity. Use await to resume on the UI thread, or Dispatcher.Invoke / Control.Invoke / MainThread.BeginInvokeOnMainThread to marshal the call.
  2. 2. In an async button handler, which thread runs the code after 'await Task.Run(...)' by default?

    UI frameworks install a SynchronizationContext. await captures it and posts the continuation back to the UI thread, unless you opt out with ConfigureAwait(false).
  3. 3. What does the 'measure' pass of XAML layout compute?

    Measure collects desired sizes bottom-up. The following Arrange pass assigns each element its final rectangle.
  4. 4. Which statement about .NET MAUI is true?

    MAUI is the successor of Xamarin.Forms: a single-project, cross-platform UI framework. Linux needs community frameworks such as Avalonia or Uno.
  5. 5. A UI event handler calls task.Result on a task whose continuation needs the UI thread. What happens?

    Blocking the UI thread on async work is a classic deadlock. Make the handler async and use await.

Summary

  • C# has several UI frameworks: WinForms (simple, Windows), WPF and WinUI (XAML, Windows), .NET MAUI (mobile plus desktop), Avalonia and Uno (cross-platform, including Linux), and Blazor Hybrid (web UI in a native shell).
  • All of them share a UI thread with an event loop, an element tree laid out by measure-then-arrange, events and commands, and (in XAML frameworks) data binding with MVVM.
  • await resumes on the UI thread through the SynchronizationContext; never touch controls from other threads and never block the UI thread on a task.
  • XAML describes the element tree, styles and templates declaratively; WPF needs a -windows target framework, MAUI needs workloads and platform SDKs.
  • Pick by platforms and team skills, keep logic in testable view-models, virtualize lists, and plan for localization and accessibility.

Next: Project: To-Do List