Skip to content

Instantly share code, notes, and snippets.

@aimore
Created May 13, 2020 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aimore/c234a8f0b41636284f35c12242e3534e to your computer and use it in GitHub Desktop.
Save aimore/c234a8f0b41636284f35c12242e3534e to your computer and use it in GitHub Desktop.
Test base command class
using System;
using System.Windows.Input;
using static System.Math;
namespace Test.ViewModels
{
public class BaseCommand : ICommand
{
public event EventHandler CanExecuteChanged;
private readonly Action<object> _action;
private readonly Action<Exception> _onExceptionAction;
private readonly TimeSpan _actionFrequency;
private readonly bool _shouldSuppressExceptions;
private DateTime _lastActionTime;
private Func<bool> _canExecute;
public BaseCommand(Action<object> action, TimeSpan? actionFrequency = null, bool shouldSuppressExceptions = false, Action<Exception> onExceptionAction = null, Func<bool> canExecute = null)
{
_action = action;
_actionFrequency = actionFrequency ?? TimeSpan.Zero;
_shouldSuppressExceptions = shouldSuppressExceptions;
_onExceptionAction = onExceptionAction;
_canExecute = canExecute;
}
public BaseCommand(Action action, TimeSpan? actionFrequency = null, bool shouldSuppressExceptions = false, Action<Exception> onExceptionAction = null, Func<bool> canExecute = null) : this(p => action?.Invoke(), actionFrequency, shouldSuppressExceptions, onExceptionAction, canExecute)
{
}
public bool CanExecute(object parameter)
=> _canExecute?.Invoke() ?? true;
public void Execute(object parameter)
{
var nowTime = DateTime.UtcNow;
if (_actionFrequency == TimeSpan.Zero
|| Abs((nowTime - _lastActionTime).TotalMilliseconds) >= _actionFrequency.TotalMilliseconds)
{
_lastActionTime = nowTime;
try
{
_action.Invoke(parameter);
}
catch (Exception ex)
{
_onExceptionAction?.Invoke(ex);
if (_shouldSuppressExceptions)
{
return;
}
throw ex;
}
}
}
public void ChangeCanExecute(bool value)
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment