| Net-Framework-QA | WPF-Routed-Events | |
Commands in WPF (Windows Presentation Foundation) |
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.
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:
public static RoutedCommand MyCommand)WPF commanding revolves around four key components:
ApplicationCommands.New)<Button Command="ApplicationCommands.New" Content="New" />
CommandBinding binding = new CommandBinding(ApplicationCommands.New); binding.Executed += NewCommand_Executed; binding.CanExecute += NewCommand_CanExecute; this.CommandBindings.Add(binding);
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
}
<Button Command="{x:Static local:MainWindow.MyCommand}" Content="Run Command" />
CanExecute enables or disables UI elements based on contextICommand in MVVM patterns | Net-Framework-QA | WPF-Routed-Events | |