// 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 command whose sole purpose is to relay its functionality to other
/// objects by invoking delegates. The default return value for the
/// method is . This type does not allow you to accept command parameters
/// in the and callback methods.
///
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 Func? canExecute;
///
public event EventHandler? CanExecuteChanged;
///
/// Initializes a new instance of the class that can always execute.
///
/// The execution logic.
/// 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.
/// Thrown if or are .
public RelayCommand(Action execute, Func 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(object? parameter)
{
return this.canExecute?.Invoke() != false;
}
///
public void Execute(object? parameter)
{
if (CanExecute(parameter))
{
this.execute();
}
}
}