/
CallMethodAction.cs
281 lines (245 loc) · 10.1 KB
/
CallMethodAction.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Xaml.Interactions.Core
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using Windows.UI.Xaml;
using Microsoft.Xaml.Interactivity;
/// <summary>
/// An action that calls a method on a specified object when invoked.
/// </summary>
public sealed class CallMethodAction : DependencyObject, IAction
{
/// <summary>
/// Identifies the <seealso cref="MethodName"/> dependency property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly DependencyProperty MethodNameProperty = DependencyProperty.Register(
"MethodName",
typeof(string),
typeof(CallMethodAction),
new PropertyMetadata(null, new PropertyChangedCallback(CallMethodAction.OnMethodNameChanged)));
/// <summary>
/// Identifies the <seealso cref="TargetObject"/> dependency property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly DependencyProperty TargetObjectProperty = DependencyProperty.Register(
"TargetObject",
typeof(object),
typeof(CallMethodAction),
new PropertyMetadata(null, new PropertyChangedCallback(CallMethodAction.OnTargetObjectChanged)));
private Type targetObjectType;
private List<MethodDescriptor> methodDescriptors = new List<MethodDescriptor>();
private MethodDescriptor cachedMethodDescriptor;
/// <summary>
/// Gets or sets the name of the method to invoke. This is a dependency property.
/// </summary>
public string MethodName
{
get
{
return (string)this.GetValue(CallMethodAction.MethodNameProperty);
}
set
{
this.SetValue(CallMethodAction.MethodNameProperty, value);
}
}
/// <summary>
/// Gets or sets the object that exposes the method of interest. This is a dependency property.
/// </summary>
public object TargetObject
{
get
{
return this.GetValue(CallMethodAction.TargetObjectProperty);
}
set
{
this.SetValue(CallMethodAction.TargetObjectProperty, value);
}
}
/// <summary>
/// Executes the action.
/// </summary>
/// <param name="sender">The <see cref="System.Object"/> that is passed to the action by the behavior. Generally this is <seealso cref="Microsoft.Xaml.Interactivity.IBehavior.AssociatedObject"/> or a target object.</param>
/// <param name="parameter">The value of this parameter is determined by the caller.</param>
/// <returns>True if the method is called; else false.</returns>
public object Execute(object sender, object parameter)
{
object target;
if (this.ReadLocalValue(CallMethodAction.TargetObjectProperty) != DependencyProperty.UnsetValue)
{
target = this.TargetObject;
}
else
{
target = sender;
}
if (target == null || string.IsNullOrEmpty(this.MethodName))
{
return false;
}
this.UpdateTargetType(target.GetType());
MethodDescriptor methodDescriptor = this.FindBestMethod(parameter);
if (methodDescriptor == null)
{
if (this.TargetObject != null)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
ResourceHelper.CallMethodActionValidMethodNotFoundExceptionMessage,
this.MethodName,
this.targetObjectType));
}
return false;
}
ParameterInfo[] parameters = methodDescriptor.Parameters;
if (parameters.Length == 0)
{
methodDescriptor.MethodInfo.Invoke(target, parameters: null);
return true;
}
else if (parameters.Length == 2)
{
methodDescriptor.MethodInfo.Invoke(target, new object[] { target, parameter });
return true;
}
return false;
}
private MethodDescriptor FindBestMethod(object parameter)
{
TypeInfo parameterTypeInfo = parameter == null ? null : parameter.GetType().GetTypeInfo();
if (parameterTypeInfo == null)
{
return this.cachedMethodDescriptor;
}
MethodDescriptor mostDerivedMethod = null;
// Loop over the methods looking for the one whose type is closest to the type of the given parameter.
foreach (MethodDescriptor currentMethod in this.methodDescriptors)
{
TypeInfo currentTypeInfo = currentMethod.SecondParameterTypeInfo;
if (currentTypeInfo.IsAssignableFrom(parameterTypeInfo))
{
if (mostDerivedMethod == null || !currentTypeInfo.IsAssignableFrom(mostDerivedMethod.SecondParameterTypeInfo))
{
mostDerivedMethod = currentMethod;
}
}
}
return mostDerivedMethod ?? this.cachedMethodDescriptor;
}
private void UpdateTargetType(Type newTargetType)
{
if (newTargetType == this.targetObjectType)
{
return;
}
this.targetObjectType = newTargetType;
this.UpdateMethodDescriptors();
}
private void UpdateMethodDescriptors()
{
this.methodDescriptors.Clear();
this.cachedMethodDescriptor = null;
if (string.IsNullOrEmpty(this.MethodName) || this.targetObjectType == null)
{
return;
}
// Find all public methods that match the given name and have either no parameters,
// or two parameters where the first is of type Object.
foreach (MethodInfo method in this.targetObjectType.GetRuntimeMethods())
{
if (string.Equals(method.Name, this.MethodName, StringComparison.Ordinal)
&& method.ReturnType == typeof(void)
&& method.IsPublic)
{
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0)
{
// There can be only one parameterless method of the given name.
this.cachedMethodDescriptor = new MethodDescriptor(method, parameters);
}
else if (parameters.Length == 2 && parameters[0].ParameterType == typeof(object))
{
this.methodDescriptors.Add(new MethodDescriptor(method, parameters));
}
}
}
// We didn't find a parameterless method, so we want to find a method that accepts null
// as a second parameter, but if we have more than one of these it is ambigious which
// we should call, so we do nothing.
if (this.cachedMethodDescriptor == null)
{
foreach (MethodDescriptor method in this.methodDescriptors)
{
TypeInfo typeInfo = method.SecondParameterTypeInfo;
if (!typeInfo.IsValueType || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
if (this.cachedMethodDescriptor != null)
{
this.cachedMethodDescriptor = null;
return;
}
else
{
this.cachedMethodDescriptor = method;
}
}
}
}
}
private static void OnMethodNameChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
CallMethodAction callMethodAction = (CallMethodAction)sender;
callMethodAction.UpdateMethodDescriptors();
}
private static void OnTargetObjectChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
CallMethodAction callMethodAction = (CallMethodAction)sender;
Type newType = args.NewValue != null ? args.NewValue.GetType() : null;
callMethodAction.UpdateTargetType(newType);
}
[DebuggerDisplay("{MethodInfo}")]
private class MethodDescriptor
{
public MethodDescriptor(MethodInfo methodInfo, ParameterInfo[] methodParameters)
{
this.MethodInfo = methodInfo;
this.Parameters = methodParameters;
}
public MethodInfo MethodInfo
{
get;
private set;
}
public ParameterInfo[] Parameters
{
get;
private set;
}
public int ParameterCount
{
get
{
return this.Parameters.Length;
}
}
public TypeInfo SecondParameterTypeInfo
{
get
{
if (this.ParameterCount < 2)
{
return null;
}
return this.Parameters[1].ParameterType.GetTypeInfo();
}
}
}
}
}