WinForms and WPF side by side

Windows has two supported desktop stacks in .NET, and a third for every platform. They answer the same question, how a window is described and drawn, in different ways, and the difference decides which one a new application should use. This lesson puts the same small screen in WinForms and in WPF, and then shows the part of the application that does not change at all.

Two desktop stacks

The four stubs are linked at the end of the course. This lesson is about the first two, because a reader who knows WinForms and meets WPF needs to know which ideas carry over.

The same screen in WinForms

A name box, a button and a greeting. The form is imperative: it creates the controls, subscribes to the click, and writes the label. Built and not run:

using System; using System.ComponentModel; using System.Drawing; using System.Runtime.CompilerServices; using System.Windows.Forms; using System.Windows.Input; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new HelloForm()); } } internal sealed class GreetingViewModel : INotifyPropertyChanged { private string _name = string.Empty; private string _greeting = string.Empty; public GreetingViewModel() { SayHello = new RelayCommand( () => Greeting = $"Hello, {Name}!", () => Name.Length > 0); } public string Name { get => _name; set { if (_name == value) { return; } _name = value; OnPropertyChanged(); SayHello.RaiseCanExecuteChanged(); } } public string Greeting { get => _greeting; private set { if (_greeting == value) { return; } _greeting = value; OnPropertyChanged(); } } public RelayCommand SayHello { get; } public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } internal sealed class RelayCommand : ICommand { private readonly Action _execute; private readonly Func<bool> _canExecute; public RelayCommand(Action execute, Func<bool> canExecute) { _execute = execute; _canExecute = canExecute; } public event EventHandler? CanExecuteChanged; public bool CanExecute(object? parameter) => _canExecute(); public void Execute(object? parameter) => _execute(); public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); } internal sealed class HelloForm : Form { private readonly GreetingViewModel _vm = new(); public HelloForm() { Text = "Hello"; ClientSize = new Size(360, 160); var name = new TextBox { Location = new Point(120, 20), Width = 200 }; var hello = new Button { Text = "Say &hello", Location = new Point(120, 56), Size = new Size(110, 27) }; var greeting = new Label { Location = new Point(16, 100), AutoSize = true }; name.DataBindings.Add( nameof(TextBox.Text), _vm, nameof(GreetingViewModel.Name), false, DataSourceUpdateMode.OnPropertyChanged); greeting.DataBindings.Add( nameof(Label.Text), _vm, nameof(GreetingViewModel.Greeting), false, DataSourceUpdateMode.Never); hello.Click += (sender, e) => _vm.SayHello.Execute(null); _vm.SayHello.CanExecuteChanged += (sender, e) => hello.Enabled = _vm.SayHello.CanExecute(null); hello.Enabled = false; Controls.Add(new Label { Text = "&Name:", AutoSize = true, Location = new Point(16, 24) }); Controls.Add(name); Controls.Add(hello); Controls.Add(greeting); } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. It is not the simplest WinForms version, because it already keeps the state in a view model: the form binds the text box to Name, binds the label to Greeting, and calls the command from a click handler. That is deliberate. The state and the rule are already separate from the controls, which is the part WPF will reuse.

The same screen in XAML

WPF describes the same screen as markup. This is not built by the course: the checker of these pages writes a WinForms project, and a WPF project needs UseWPF and its own build. The XAML is shown as the description of the screen, not as a listing that was compiled:

<Window x:Class="Hello.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Hello" Width="360" Height="160"> <StackPanel Margin="16"> <StackPanel Orientation="Horizontal"> <Label Content="Name:" /> <TextBox Width="200" Margin="8,0,0,0" Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" /> </StackPanel> <Button Content="Say hello" Margin="0,8,0,0" Width="110" HorizontalAlignment="Left" Command="{Binding SayHello}" /> <TextBlock Text="{Binding Greeting}" Margin="0,16,0,0" /> </StackPanel> </Window>

Three things are different and each is the reason for the other two. The layout is a tree of panels with margins, not a set of coordinates: the window can resize and the controls re-measure themselves. The text box is bound with a binding expression, and the button is connected to a command rather than to a click handler, so the view has no code for either. And the button disables itself when CanExecute is false, without the line that sets Enabled in the WinForms listing.

The code-behind of the window is short: it sets the data context, which is the view model, and nothing else. The XAML compiler generates the InitializeComponent equivalent at build time, and that generated code is why a WPF build needs the WPF targets even for a window with no logic.

The part both stacks share

The view model and the command are plain .NET: INotifyPropertyChanged, ICommand and a lambda. The program below drives them with no window, so it runs here. It was built and run in the container:

using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Input; Console.WriteLine("a view model both stacks can use"); var vm = new GreetingViewModel(); vm.PropertyChanged += (sender, e) => Console.WriteLine($"changed: {e.PropertyName}"); Console.WriteLine($"can say hello: {vm.SayHello.CanExecute(null)}"); vm.Name = "Ada"; Console.WriteLine($"can say hello: {vm.SayHello.CanExecute(null)}"); vm.SayHello.Execute(null); Console.WriteLine($"greeting: {vm.Greeting}"); vm.Name = "Grace"; Console.WriteLine($"greeting after a rename: {vm.Greeting}"); internal sealed class GreetingViewModel : INotifyPropertyChanged { private string _name = string.Empty; private string _greeting = string.Empty; public GreetingViewModel() { SayHello = new RelayCommand( () => Greeting = $"Hello, {Name}!", () => Name.Length > 0); } public string Name { get => _name; set { if (_name == value) { return; } _name = value; OnPropertyChanged(); SayHello.RaiseCanExecuteChanged(); } } public string Greeting { get => _greeting; private set { if (_greeting == value) { return; } _greeting = value; OnPropertyChanged(); } } public RelayCommand SayHello { get; } public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } internal sealed class RelayCommand : ICommand { private readonly Action _execute; private readonly Func<bool> _canExecute; public RelayCommand(Action execute, Func<bool> canExecute) { _execute = execute; _canExecute = canExecute; } public event EventHandler? CanExecuteChanged; public bool CanExecute(object? parameter) => _canExecute(); public void Execute(object? parameter) => _execute(); public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); }

dotnet run

a view model both stacks can use
can say hello: False
changed: Name
can say hello: True
changed: Greeting
greeting: Hello, Ada!
changed: Name
greeting after a rename: Hello, Ada!

The output is the real run. The command could not execute while the name was empty, and it enabled itself when the setter raised CanExecuteChanged. The greeting changed only when the command ran, and a later rename left it as it was: Greeting is a stored value here, not a computed one, which is the difference the two stacks behave the same way about. Both bindings read it and both need the event.

That class is the argument for the whole Structure and testing part: the part of a screen that is worth testing does not know which stack draws it. A WinForms form, a WPF window and a MAUI page can all bind the same view model, and the view model can be tested here, on Linux, with no display.

Which one to choose

One technical fact decides more than the marketing: a WinForms control is an HWND, so hosting it in WPF needs WindowsFormsHost, and hosting WPF in WinForms needs ElementHost. Neither crosses the boundary for free, which is why a mixed application is a deliberate architecture and not an accident. The WPF course takes the other side from here.

Exercises

  1. Add a Clear command to the view model with the same RelayCommand and explain what the button in each stack needs.
  2. Make Greeting a computed property and change the events the view model raises; compare the output with the run above.
  3. List three screens of an application you know and say which stack you would choose for each, with one sentence of reason.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How does WinForms draw a control?

    Answer

    Immediately, when the control asks for a paint, through GDI+

    WPF is the retained-mode stack of the two.

  2. What is a WinForms control in terms of the operating system?

    Answer

    A window with a handle, an HWND

    The handle is why only the owning thread may touch it.

  3. How is a button connected in XAML?

    Answer

    With a Command binding to an ICommand

    The command also drives the disabled state through CanExecute.

  4. Which part of the application can both stacks share?

    Answer

    The view model and its commands

    Both bind to INotifyPropertyChanged and ICommand.

  5. What did the run print before the name was set?

    Answer

    can say hello: False

    CanExecute was false while Name was empty.

  6. Why did the greeting stay "Hello, Ada!" after the rename?

    Answer

    Greeting is a stored value set by the command, not computed from Name

    The run shows the second Name change did not touch Greeting.

  7. Which line enables the WinForms button when the name is filled?

    Answer

    The CanExecuteChanged handler that sets Enabled

    WPF does that from the command; WinForms needs the line.

  8. What does the XAML layout use instead of coordinates?

    Answer

    A tree of panels with margins

    The panels measure and arrange the children.

  9. What does hosting a WinForms control in WPF need?

    Answer

    WindowsFormsHost

    ElementHost is the other direction.

  10. When is MAUI the right choice?

    Answer

    When the same screens must run on Windows and a phone

    A desktop-only application gains nothing from it.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs. The XAML is markup, not a C# listing, and is shown for comparison: a WPF project needs UseWPF, which this course's build does not set.

Article author: Arthur Isaev