90 строки
2.7 KiB
C#
90 строки
2.7 KiB
C#
// 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.
|
|
|
|
using System;
|
|
using System.Diagnostics;
|
|
using System.Windows.Input;
|
|
|
|
namespace CommunityToolkit.WinUI.SampleApp.Common
|
|
{
|
|
public class DelegateCommand<T> : ICommand
|
|
{
|
|
private readonly Action<T> commandExecuteAction;
|
|
|
|
private readonly Func<T, bool> commandCanExecute;
|
|
|
|
public DelegateCommand(Action<T> executeAction, Func<T, bool> canExecute = null)
|
|
{
|
|
if (executeAction == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(executeAction));
|
|
}
|
|
|
|
commandExecuteAction = executeAction;
|
|
commandCanExecute = canExecute ?? (e => true);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Occurs when changes occur that affect whether or not the command should execute.
|
|
/// </summary>
|
|
public event EventHandler CanExecuteChanged;
|
|
|
|
/// <summary>
|
|
/// Defines the method that determines whether the command can execute in its current state.
|
|
/// </summary>
|
|
/// <param name="parameter">
|
|
/// The parameter used by the command.
|
|
/// </param>
|
|
/// <returns>
|
|
/// Returns a value indicating whether this command can be executed.
|
|
/// </returns>
|
|
public bool CanExecute(object parameter)
|
|
{
|
|
try
|
|
{
|
|
return commandCanExecute(ConvertParameterValue(parameter));
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine($"Action failed {e}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Defines the method to be called when the command is invoked.
|
|
/// </summary>
|
|
/// <param name="parameter">
|
|
/// The parameter used by the command.
|
|
/// </param>
|
|
public void Execute(object parameter)
|
|
{
|
|
if (!CanExecute(parameter))
|
|
{
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
commandExecuteAction(ConvertParameterValue(parameter));
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Console.WriteLine($"Action failed {e}");
|
|
Debugger.Break();
|
|
}
|
|
}
|
|
|
|
public void RaiseCanExecuteChanged()
|
|
{
|
|
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
|
|
}
|
|
|
|
private static T ConvertParameterValue(object parameter)
|
|
{
|
|
parameter = parameter is T ? parameter : Convert.ChangeType(parameter, typeof(T));
|
|
return (T)parameter;
|
|
}
|
|
}
|
|
} |