-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathCommandRelay.cs
113 lines (96 loc) · 2.7 KB
/
CommandRelay.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WPFRssFeedReader
{
public class CommandRelay<T> : ICommand
{
#region Fields
private Func<T, bool> shouldExecute;
private Action<T> run;
private bool lastCanExecute;
#endregion
#region Constructors
public CommandRelay() : this(null, null)
{
}
public CommandRelay(Func<T, bool> _shouldExecute, Action<T> _run)
{
lastCanExecute = false;
shouldExecute = _shouldExecute;
run = _run;
}
#endregion
#region ICommand Members
public bool CanExecute(object parameter)
{
bool result = lastCanExecute;
bool oldVal = lastCanExecute;
bool newVal = lastCanExecute;
if(null != shouldExecute)
{
result = shouldExecute((T)parameter);
newVal = result;
}
if (oldVal != newVal)
{
CanExecuteChangedEventArgs args = new CanExecuteChangedEventArgs(oldVal, newVal);
OnCanExecuteChanged(this, args);
}
lastCanExecute = result;
return result;
}
public void Execute(object parameter)
{
if(null != run)
{
run((T)parameter);
}
}
#endregion
#region Events
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
#endregion
#region Events Handlers
protected virtual void OnCanExecuteChanged(object sender, EventArgs e)
{
}
#endregion
}
public class CommandRelay : CommandRelay<Object>
{
#region Constructors
public CommandRelay(): base(null, null)
{
}
public CommandRelay(Func<object, bool> _shouldExecute, Action<object> _run)
: base(_shouldExecute, _run)
{
}
#endregion
}
public class CanExecuteChangedEventArgs : EventArgs
{
#region Fields And Properties
public bool OldVal { get; set; }
public bool NewVal { get; set; }
#endregion
#region Constructors
public CanExecuteChangedEventArgs()
{
}
public CanExecuteChangedEventArgs(bool _oldVal, bool _newVal)
{
OldVal = _oldVal;
NewVal = _newVal;
}
#endregion
}
}