WPF layout and binding
WPF layout and binding
WPF is a Windows desktop UI framework. XAML declares the visual tree, a binding transfers values between controls and a source, and a view model owns presentation state and actions. Separating these roles makes inventory behavior testable without launching a window.
Grid distributes space through rows and columns; Auto sizes to content and star sizing allocates remaining space. StackPanel arranges children along an axis. Use margins, minimum sizes and scrollable regions rather than fixing every coordinate. Binding uses a source, path, target property and direction. DataContext is inherited by many descendants. INotifyPropertyChanged signals changed scalar properties, while ObservableCollection reports collection changes (not arbitrary item property changes). WPF TextBox.Text commonly updates its source on lost focus unless UpdateSourceTrigger is changed. ICommand represents an action and availability; CanExecute is not an authorization boundary. Raise CanExecuteChanged when command availability changes, and let consumers requery it. Direct calls to Execute are not automatically guarded by the interface. For a custom command, validate the domain operation independently. Notify dependent calculated properties when their inputs change; collection-change notifications do not replace item-level notifications. MVVM separates display markup, state and actions, not necessarily every line of code-behind. Resource dictionaries centralize styles; use system-aware colors and verify high contrast. WPF and WinForms are Windows-only. WinUI is a different Windows framework; Avalonia is a separate cross-platform product with its own API and lifecycle. Review packaging, signing and update strategy separately.
Baseline: .NET 10 / C# 14. Every expected result is reasoned, not executed. The complete portable and Windows desktop projects are separate from MAUI template overlays. No runtime or UI claims.
Bind an inventory field in two columns
Type Bolts into the field. The preview should change as you type.
Use an approved Windows .NET 10 environment. Build the complete Fixture.csproj after approved restore; run it and close the window when finished.
using System;using System.Windows;namespace Fixture;public static class Program { [STAThread] public static void Main() => new Application().Run(new InventoryWindow());}public partial class InventoryWindow : Window { public InventoryWindow() { InitializeComponent(); DataContext = new InventoryState(); }}public sealed class InventoryState : System.ComponentModel.INotifyPropertyChanged { private string name = "Nuts"; public string Name { get => name; set { if (name == value) return; name = value; PropertyChanged?.Invoke(this,new(nameof(Name))); } } public event System.ComponentModel.PropertyChangedEventHandler? PropertyChanged;}InventoryWindow.xaml
<Window x:Class="Fixture.InventoryWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Inventory lab" Width="440" Height="260" MinWidth="320" MinHeight="220"> <Grid Margin="16"> Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> /Grid.ColumnDefinitions> Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> /Grid.RowDefinitions> <Label Target="{Binding ElementName=NameBox}" Content="_Item name"/> <TextBox x:Name="NameBox" Grid.Column="1" Margin="8" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/> <TextBlock Grid.Row="1" Grid.Column="1" Margin="8" Text="{Binding Name}"/> </Grid></Window>Expected result (not executed):
Initially Nuts; typing Bolts changes the preview to Bolts.The TextBox writes the property and its notification refreshes the TextBlock. The label provides a keyboard mnemonic and a target.
Bind a collection and command
Select Add sample twice; verify the list adds two rows.
Use an approved Windows .NET 10 environment. Build the complete Fixture.csproj after approved restore; run it and close the window when finished.
using System;using System.Windows;namespace Fixture;public static class Program { [STAThread] public static void Main() => new Application().Run(new InventoryWindow());}public partial class InventoryWindow : Window { public InventoryWindow() { InitializeComponent(); DataContext = new InventoryModel(); }}public sealed class InventoryModel { public System.Collections.ObjectModel.ObservableCollection<string> Items { get; } = new() { "Nuts" }; public System.Windows.Input.ICommand Add { get; } public InventoryModel() { Add = new ActionCommand(() => Items.Add("Bolt")); }}public sealed class ActionCommand(Action action) : System.Windows.Input.ICommand { public event EventHandler? CanExecuteChanged { add { } remove { } } public bool CanExecute(object? parameter) => true; public void Execute(object? parameter) => action();}InventoryWindow.xaml
<Window x:Class="Fixture.InventoryWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Inventory lab" Width="440" Height="260" MinWidth="320" MinHeight="220"> <DockPanel Margin="16"> <Button DockPanel.Dock="Top" Margin="0,0,0,8" Content="_Add sample" Command="{Binding Add}"/> <ListBox ItemsSource="{Binding Items}" AutomationProperties.Name="Inventory items"/> </DockPanel></Window>Expected result (not executed):
Nuts, Bolt, Bolt in order.The command is always enabled for this bounded manual walkthrough. A real inventory uses unique IDs, limits and a policy for duplicate items.
Verify presentation state without WPF
This small model demonstrates a notification and no-op suppression.
Use the complete Fixture.csproj with an approved .NET 10 SDK. Restore approved dependencies, build and run. No UI workload needed.
using System;using System.ComponentModel;var state = new Stock();int changes = 0;state.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(Stock.Quantity)) changes++; };state.Quantity = 3;state.Quantity = 3;Console.WriteLine($"Quantity={state.Quantity}; changes={changes}");sealed class Stock : INotifyPropertyChanged { private int quantity; public int Quantity { get => quantity; set { if (quantity == value) return; quantity = value; PropertyChanged?.Invoke(this,new(nameof(Quantity))); } } public event PropertyChangedEventHandler? PropertyChanged;}Expected result (not executed):
Quantity=3; changes=1The notification contract can be checked without WPF, but XAML binding resolution and focus still need a Windows UI test.
Apply the concept
Sketch a two-column inventory editor with item name, quantity, list and add action. Specify binding modes, invalid quantities and keyboard order.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
WPF layout and binding — knowledge check
Apply the lesson concepts to the following scenarios.
Where should presentation state live in MVVM?
What notifies WPF about changed scalar model properties?
What does ObservableCollection primarily report?
Which Grid column width consumes available remaining space?
What is still needed after a view-model test passes?