Catalog/imagecatalog/Commands/ButtonCommandBinder.cs

53 lines
1.9 KiB
C#
Raw Normal View History

2026-02-04 23:16:06 +01:00
using System;
using System.Windows.Forms;
using System.Windows.Input;
namespace ImageCatalog_2.Commands
{
/// <summary>
/// Helper class to bind WinForms Button controls to ICommand implementations
/// </summary>
public static class ButtonCommandBinder
{
/// <summary>
/// Binds a Button's Click event to an ICommand
/// </summary>
/// <param name="button">The button to bind</param>
/// <param name="command">The command to execute</param>
/// <param name="commandParameter">Optional parameter to pass to the command</param>
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);
}
/// <summary>
/// Binds multiple buttons to commands at once
/// </summary>
public static void BindCommands(params (Button button, ICommand command, object parameter)[] bindings)
{
foreach (var (button, command, parameter) in bindings)
{
button.BindCommand(command, parameter);
}
}
}
}