markus / MarkusAutoUpdate / src / NetSparkle.UI.WPF / Helpers / RelayCommand.cs @ 8e3d58f3
이력 | 보기 | 이력해설 | 다운로드 (1.67 KB)
1 |
using System; |
---|---|
2 |
using System.Collections.Generic; |
3 |
using System.Diagnostics; |
4 |
using System.Linq; |
5 |
using System.Text; |
6 |
using System.Threading.Tasks; |
7 |
using System.Windows.Input; |
8 | |
9 |
namespace WPFTemplate.Helpers |
10 |
{ |
11 |
// https://gist.github.com/schuster-rainer/2648922 with some modifications |
12 |
public class RelayCommand<T> : ICommand |
13 |
{ |
14 |
#region Fields |
15 | |
16 |
readonly Action<T> _execute; |
17 |
readonly Predicate<T> _canExecute; |
18 | |
19 |
#endregion |
20 | |
21 |
#region Constructors |
22 | |
23 |
public RelayCommand(Action<T> execute) |
24 |
: this(execute, null) |
25 |
{ |
26 |
} |
27 | |
28 |
public RelayCommand(Action<T> execute, Predicate<T> canExecute) |
29 |
{ |
30 |
if (execute == null) |
31 |
throw new ArgumentNullException("Execute parameter cannot be null"); |
32 |
_execute = execute; |
33 |
_canExecute = canExecute; |
34 |
} |
35 | |
36 |
#endregion |
37 | |
38 |
#region ICommand Members |
39 | |
40 |
[DebuggerStepThrough] |
41 |
public bool CanExecute(object parameter) |
42 |
{ |
43 |
return _canExecute == null ? true : _canExecute((T)parameter); |
44 |
} |
45 | |
46 |
public event EventHandler CanExecuteChanged |
47 |
{ |
48 |
add { CommandManager.RequerySuggested += value; } |
49 |
remove { CommandManager.RequerySuggested -= value; } |
50 |
} |
51 | |
52 |
public void Execute(object parameter) => _execute((T)parameter); |
53 | |
54 |
#endregion |
55 |
} |
56 | |
57 |
public class RelayCommand : RelayCommand<object> |
58 |
{ |
59 |
public RelayCommand(Action execute) : this(execute, null) { } |
60 |
public RelayCommand(Action execute, Func<bool> canExecute) |
61 |
: base(param => execute?.Invoke(), |
62 |
param => (canExecute?.Invoke()) ?? true) { } |
63 |
} |
64 |
} |