-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommand.cs
76 lines (66 loc) · 2.67 KB
/
Command.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Windows.Input;
namespace Common
{
/// <summary>
/// This class simplifies the ability for Binding commands to WPF actions. It supports commands from the View
/// to the ViewModel including passing a parameter. To avoid encountering conflicts between the command, action,
/// and method signatures, it is recommended to use "[operation]Command", "[operation]Action", and "[operation]"
/// for the respective Command, Action, and Method. See the example, below.
///
/// XAML:
/// <Button Content="Load" Command="{Binding ShowPersonCommand}" CommandParameter="{Binding SelectedPerson}" />
///
/// ViewModel:
/// public ICommand ShowPersonCommand { get; set; }
///
/// ShowPersonCommand = new Command(ShowPersonAction);
///
/// private void ShowPersonAction(object obj) => ShowPersion((Person)obj);
///
/// private void ShowPerson(Person person) => MessageBox.Show("Person",$"The selected person is {person.FullName}");
///
/// </summary>
public class Command : ICommand
{
private Action<object> execute;
private Predicate<object> canExecute;
private event EventHandler CanExecuteChangedInternal;
public Command(Action<object> execute) : this(execute, DefaultCanExecute) { }
public Command(Action<object> execute, Predicate<object> canExecute)
{
this.execute = execute ?? throw new ArgumentNullException("execute");
this.canExecute = canExecute ?? throw new ArgumentNullException("canExecute");
}
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
CanExecuteChangedInternal += value;
}
remove
{
CommandManager.RequerySuggested -= value;
CanExecuteChangedInternal -= value;
}
}
public bool CanExecute(object parameter) => canExecute != null && canExecute(parameter);
public void Execute(object parameter) => execute(parameter);
public void OnCanExecuteChanged()
{
EventHandler handler = CanExecuteChangedInternal;
if (handler != null)
{
//DispatcherHelper.BeginInvokeOnUIThread(() => handler.Invoke(this, EventArgs.Empty));
handler.Invoke(this, EventArgs.Empty);
}
}
public void Destroy()
{
canExecute = _ => false;
execute = _ => { return; };
}
private static bool DefaultCanExecute(object parameter) => true;
}
}