*
Previous Net-Framework-QA WPF-Routed-Events Next

Commands in WPF (Windows Presentation Foundation)

WPF Commands

Commands in WPF are a powerful abstraction that decouples user actions from the logic that executes them. Instead of wiring up click events manually, you can use commands to centralize and reuse logic across multiple UI elements like buttons, menus, and keyboard shortcuts.

đź§  What Are Commands in WPF?

Commands represent semantic actions—like Copy, Paste, Save, or Delete—rather than low-level input events. WPF provides a built-in commanding infrastructure that includes:

  • Predefined commands (e.g., ApplicationCommands.Copy)
  • Custom commands (e.g., public static RoutedCommand MyCommand)
  • Command bindings to link UI elements with logic

⚙️ How Commands Work in WPF

WPF commanding revolves around four key components:

  1. Command Object – Represents the action (e.g., ApplicationCommands.New)
  2. Command Source – UI element that triggers the command (e.g., Button, MenuItem)
  3. Command Target – The object that receives the command (often inferred automatically)
  4. Command Binding – Connects the command to the logic via Executed and CanExecute handlers

Visual Diagram

Command Object Command Source Command Target Command Binding

Example in XAML

<Button Command="ApplicationCommands.New" Content="New" />
  

Example in C#

CommandBinding binding = new CommandBinding(ApplicationCommands.New);
binding.Executed += NewCommand_Executed;
binding.CanExecute += NewCommand_CanExecute;
this.CommandBindings.Add(binding);
  

đź§Ş Example: Custom RoutedCommand

public static RoutedCommand MyCommand = new RoutedCommand();

public MainWindow()
{
    CommandBinding cb = new CommandBinding(MyCommand, ExecuteMyCommand, CanExecuteMyCommand);
    this.CommandBindings.Add(cb);
}

private void ExecuteMyCommand(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Command executed!");
}

private void CanExecuteMyCommand(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true; // or some condition
}
  

And in XAML:

<Button Command="{x:Static local:MainWindow.MyCommand}" Content="Run Command" />
  

🎯 Why Use Commands?

  • Reusability: Same logic can be triggered from multiple sources (button, menu, shortcut)
  • Separation of concerns: Keeps UI and logic cleanly separated
  • State awareness: CanExecute enables or disables UI elements based on context
  • MVVM-friendly: Commands integrate well with ICommand in MVVM patterns
Back to Index
Previous Net-Framework-QA WPF-Routed-Events Next
*
*