// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// This file is inspired from the MvvmLight library (lbugnion/MvvmLight),
// more info in ThirdPartyNotices.txt in the root of the project.
using System;
using System.Runtime.CompilerServices;
namespace CommunityToolkit.Mvvm.Input;
///
/// A generic command whose sole purpose is to relay its functionality to other
/// objects by invoking delegates. The default return value for the CanExecute
/// method is . This class allows you to accept command parameters
/// in the and callback methods.
///
/// The type of parameter being passed as input to the callbacks.
public sealed class RelayCommand : IRelayCommand
{
///
/// The to invoke when is used.
///
private readonly Action execute;
///
/// The optional action to invoke when is used.
///
private readonly Predicate? canExecute;
///
public event EventHandler? CanExecuteChanged;
///
/// Initializes a new instance of the class that can always execute.
///
/// The execution logic.
///
/// Due to the fact that the interface exposes methods that accept a
/// nullable parameter, it is recommended that if is a reference type,
/// you should always declare it as nullable, and to always perform checks within .
///
/// Thrown if is .
public RelayCommand(Action execute)
{
ArgumentNullException.ThrowIfNull(execute);
this.execute = execute;
}
///
/// Initializes a new instance of the class.
///
/// The execution logic.
/// The execution status logic.
/// See notes in .
/// Thrown if or are .
public RelayCommand(Action execute, Predicate canExecute)
{
ArgumentNullException.ThrowIfNull(execute);
ArgumentNullException.ThrowIfNull(canExecute);
this.execute = execute;
this.canExecute = canExecute;
}
///
public void NotifyCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanExecute(T? parameter)
{
return this.canExecute?.Invoke(parameter) != false;
}
///
public bool CanExecute(object? parameter)
{
if (default(T) is not null &&
parameter is null)
{
return false;
}
return CanExecute((T?)parameter);
}
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Execute(T? parameter)
{
this.execute(parameter);
}
///
public void Execute(object? parameter)
{
Execute((T?)parameter);
}
}