using System;
using System.Windows.Forms;
using System.Windows.Input;
namespace ImageCatalog_2.Commands
{
///
/// Helper class to bind WinForms Button controls to ICommand implementations
///
public static class ButtonCommandBinder
{
///
/// Binds a Button's Click event to an ICommand
///
/// The button to bind
/// The command to execute
/// Optional parameter to pass to the command
public static void BindCommand(this Button button, ICommand command, object commandParameter = null)
{
if (button == null) throw new ArgumentNullException(nameof(button));
if (command == null) throw new ArgumentNullException(nameof(command));
// Wire up the Click event to execute the command
button.Click += (sender, e) =>
{
if (command.CanExecute(commandParameter))
{
command.Execute(commandParameter);
}
};
// Wire up CanExecuteChanged to enable/disable the button
command.CanExecuteChanged += (sender, e) =>
{
button.Enabled = command.CanExecute(commandParameter);
};
// Set initial enabled state
button.Enabled = command.CanExecute(commandParameter);
}
///
/// Binds multiple buttons to commands at once
///
public static void BindCommands(params (Button button, ICommand command, object parameter)[] bindings)
{
foreach (var (button, command, parameter) in bindings)
{
button.BindCommand(command, parameter);
}
}
}
}