- Voeg RelayCommand class toe voor herbruikbare ICommand implementatie - Vervang button click event handler door AddProductCommand in MainViewModel - Update XAML om Command binding te gebruiken in plaats van Click event - Verwijder business logic uit code-behind (MainWindow.xaml.cs) - Los DataContext duplicatie op (was twee keer MainViewModel instantie) Dit maakt de applicatie beter testbaar en volgt proper MVVM principes. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
63 lines
2.3 KiB
C#
63 lines
2.3 KiB
C#
using System;
|
|
using System.Windows.Input;
|
|
|
|
namespace MVVM_DEMO.Commands
|
|
{
|
|
/// <summary>
|
|
/// A command whose sole purpose is to relay its functionality to other objects by invoking delegates.
|
|
/// The default return value for the CanExecute method is 'true'.
|
|
/// </summary>
|
|
public class RelayCommand : ICommand
|
|
{
|
|
private readonly Action<object?> _execute;
|
|
private readonly Func<object?, bool>? _canExecute;
|
|
|
|
/// <summary>
|
|
/// Occurs when changes occur that affect whether or not the command should execute.
|
|
/// </summary>
|
|
public event EventHandler? CanExecuteChanged
|
|
{
|
|
add { CommandManager.RequerySuggested += value; }
|
|
remove { CommandManager.RequerySuggested -= value; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a new command that can always execute.
|
|
/// </summary>
|
|
/// <param name="execute">The execution logic.</param>
|
|
public RelayCommand(Action<object?> execute) : this(execute, null)
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates a new command.
|
|
/// </summary>
|
|
/// <param name="execute">The execution logic.</param>
|
|
/// <param name="canExecute">The execution status logic.</param>
|
|
public RelayCommand(Action<object?> execute, Func<object?, bool>? canExecute)
|
|
{
|
|
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
|
|
_canExecute = canExecute;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Determines whether this command can execute in its current state.
|
|
/// </summary>
|
|
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
|
|
/// <returns>true if this command can be executed; otherwise, false.</returns>
|
|
public bool CanExecute(object? parameter)
|
|
{
|
|
return _canExecute == null || _canExecute(parameter);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Executes the command.
|
|
/// </summary>
|
|
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
|
|
public void Execute(object? parameter)
|
|
{
|
|
_execute(parameter);
|
|
}
|
|
}
|
|
}
|