-
Notifications
You must be signed in to change notification settings - Fork 774
Expand file tree
/
Copy pathViewModelBinder.cs
More file actions
294 lines (253 loc) · 11.9 KB
/
ViewModelBinder.cs
File metadata and controls
294 lines (253 loc) · 11.9 KB
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
282
283
284
285
286
287
288
289
290
291
292
293
294
#if XFORMS
namespace Caliburn.Micro.Xamarin.Forms
#elif MAUI
namespace Caliburn.Micro.Maui
#else
namespace Caliburn.Micro
#endif
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using System.Text;
#if XFORMS
using UIElement = global::Xamarin.Forms.Element;
using FrameworkElement = global::Xamarin.Forms.VisualElement;
using DependencyProperty = global::Xamarin.Forms.BindableProperty;
using DependencyObject = global::Xamarin.Forms.BindableObject;
#elif MAUI
using UIElement = global::Microsoft.Maui.Controls.Element;
using FrameworkElement = global::Microsoft.Maui.Controls.VisualElement;
using DependencyProperty = global::Microsoft.Maui.Controls.BindableProperty;
using DependencyObject = global::Microsoft.Maui.Controls.BindableObject;
#elif WINDOWS_UWP
using Windows.UI.Xaml;
using Microsoft.Xaml.Interactivity;
#elif AVALONIA
using Avalonia;
using Avalonia.Controls;
using FrameworkElement = Avalonia.Controls.Control;
using DependencyObject = Avalonia.AvaloniaObject;
using DependencyProperty = Avalonia.AvaloniaProperty;
#elif WinUI3
using Microsoft.UI.Xaml;
using Microsoft.Xaml.Interactivity;
#else
using System.Windows;
using Microsoft.Xaml.Behaviors;
#endif
/// <summary>
/// Binds a view to a view model.
/// </summary>
public static class ViewModelBinder {
const string AsyncSuffix = "Async";
static readonly ILog Log = LogManager.GetLog(typeof(ViewModelBinder));
/// <summary>
/// Gets or sets a value indicating whether to apply conventions by default.
/// </summary>
/// <value>
/// <c>true</c> if conventions should be applied by default; otherwise, <c>false</c>.
/// </value>
public static bool ApplyConventionsByDefault = true;
/// <summary>
/// Indicates whether or not the conventions have already been applied to the view.
/// </summary>
public static readonly DependencyProperty ConventionsAppliedProperty =
#if AVALONIA
AvaloniaProperty.RegisterAttached<AvaloniaObject, bool>("ConventionsApplied", typeof(ViewModelBinder));
#else
DependencyPropertyHelper.RegisterAttached(
"ConventionsApplied",
typeof(bool),
typeof(ViewModelBinder),
false
);
#endif
/// <summary>
/// Determines whether a view should have conventions applied to it.
/// </summary>
/// <param name="view">The view to check.</param>
/// <returns>Whether or not conventions should be applied to the view.</returns>
public static bool ShouldApplyConventions(FrameworkElement view) {
var overriden = View.GetApplyConventions(view);
return overriden.GetValueOrDefault(ApplyConventionsByDefault);
}
/// <summary>
/// Creates data bindings on the view's controls based on the provided properties.
/// </summary>
/// <remarks>Parameters include named Elements to search through and the type of view model to determine conventions for. Returns unmatched elements.</remarks>
public static Func<IEnumerable<FrameworkElement>, Type, IEnumerable<FrameworkElement>> BindProperties = (namedElements, viewModelType) => {
var unmatchedElements = new List<FrameworkElement>();
#if !XFORMS && !MAUI
foreach (var element in namedElements) {
var cleanName = element.Name.Trim('_');
var parts = cleanName.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
var property = viewModelType.GetPropertyCaseInsensitive(parts[0]);
var interpretedViewModelType = viewModelType;
for (int i = 1; i < parts.Length && property != null; i++) {
interpretedViewModelType = property.PropertyType;
property = interpretedViewModelType.GetPropertyCaseInsensitive(parts[i]);
}
if (property == null) {
unmatchedElements.Add(element);
Log.Info("Binding Convention Not Applied: Element {0} did not match a property.", element.Name);
continue;
}
var convention = ConventionManager.GetElementConvention(element.GetType());
if (convention == null) {
unmatchedElements.Add(element);
Log.Warn("Binding Convention Not Applied: No conventions configured for {0}.", element.GetType());
continue;
}
var applied = convention.ApplyBinding(
interpretedViewModelType,
cleanName.Replace('_', '.'),
property,
element,
convention
);
if (applied) {
Log.Info("Binding Convention Applied: Element {0}.", element.Name);
}
else {
Log.Info("Binding Convention Not Applied: Element {0} has existing binding.", element.Name);
unmatchedElements.Add(element);
}
}
#endif
return unmatchedElements;
};
/// <summary>
/// Attaches instances of <see cref="ActionMessage"/> to the view's controls based on the provided methods.
/// </summary>
/// <remarks>Parameters include the named elements to search through and the type of view model to determine conventions for. Returns unmatched elements.</remarks>
public static Func<IEnumerable<FrameworkElement>, Type, IEnumerable<FrameworkElement>> BindActions = (namedElements, viewModelType) => {
var unmatchedElements = namedElements.ToList();
#if !XFORMS && !MAUI
#if WINDOWS_UWP || XFORMS || MAUI
var methods = viewModelType.GetRuntimeMethods();
#else
var methods = viewModelType.GetMethods();
#endif
foreach (var method in methods) {
Log.Info($"Searching for methods control {method.Name} unmatchedElements count {unmatchedElements.Count}");
var foundControl = unmatchedElements.FindName(method.Name);
if (foundControl == null && IsAsyncMethod(method)) {
var methodNameWithoutAsyncSuffix = method.Name.Substring(0, method.Name.Length - AsyncSuffix.Length);
foundControl = unmatchedElements.FindName(methodNameWithoutAsyncSuffix);
}
if(foundControl == null) {
Log.Info("Action Convention Not Applied: No actionable element for {0}. {1}", method.Name, unmatchedElements.Count);
foreach(var element in unmatchedElements)
{
Log.Info($"Unnamed element {element.Name}");
}
continue;
}
unmatchedElements.Remove(foundControl);
#if WINDOWS_UWP
var triggers = Interaction.GetBehaviors(foundControl);
if (triggers != null && triggers.Count > 0)
{
Log.Info("Action Convention Not Applied: Interaction.Triggers already set on {0}.", foundControl.Name);
continue;
}
#endif
var parameters = method.GetParameters();
var messageBuilder = new StringBuilder(method.Name);
if (parameters.Length > 0) {
messageBuilder.Append("(");
foreach (var parameter in parameters) {
var paramName = parameter.Name;
var specialValue = "$" + paramName.ToLower();
if (MessageBinder.SpecialValues.ContainsKey(specialValue))
paramName = specialValue;
messageBuilder.Append(paramName).Append(",");
}
// Remove the trailing comma
if (parameters.Length > 0)
messageBuilder.Length -= 1;
messageBuilder.Append(")");
var message = messageBuilder.ToString();
}
Log.Info("Action Convention Applied: Action {0} on element {1}.", method.Name, message);
Message.SetAttach(foundControl, message);
}
#endif
return unmatchedElements;
};
static bool IsAsyncMethod(MethodInfo method) {
return typeof(Task).GetTypeInfo().IsAssignableFrom(method.ReturnType.GetTypeInfo()) &&
method.Name.EndsWith(AsyncSuffix, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Allows the developer to add custom handling of named elements which were not matched by any default conventions.
/// </summary>
public static Action<IEnumerable<FrameworkElement>, Type> HandleUnmatchedElements = (elements, viewModelType) => { };
/// <summary>
/// Binds the specified viewModel to the view.
/// </summary>
///<remarks>Passes the the view model, view and creation context (or null for default) to use in applying binding.</remarks>
public static Action<object, DependencyObject, object> Bind = (viewModel, view, context) => {
#if !WINDOWS_UWP && !XFORMS && !MAUI
// when using d:DesignInstance, Blend tries to assign the DesignInstanceExtension class as the DataContext,
// so here we get the actual ViewModel which is in the Instance property of DesignInstanceExtension
if (View.InDesignMode) {
var vmType = viewModel.GetType();
if (vmType.FullName == "Microsoft.Expression.DesignModel.InstanceBuilders.DesignInstanceExtension") {
var propInfo = vmType.GetProperty("Instance", BindingFlags.Instance | BindingFlags.NonPublic);
viewModel = propInfo.GetValue(viewModel, null);
}
}
#endif
Log.Info("Binding {0} and {1}.", view, viewModel);
#if XFORMS
var noContext = Caliburn.Micro.Xamarin.Forms.Bind.NoContextProperty;
#elif MAUI
var noContext = Caliburn.Micro.Maui.Bind.NoContextProperty;
#else
var noContext = Caliburn.Micro.Bind.NoContextProperty;
#endif
if ((bool)view.GetValue(noContext)) {
Action.SetTargetWithoutContext(view, viewModel);
}
else {
Action.SetTarget(view, viewModel);
}
var viewAware = viewModel as IViewAware;
if (viewAware != null) {
Log.Info("Attaching {0} to {1}.", view, viewAware);
viewAware.AttachView(view, context);
}
if ((bool)view.GetValue(ConventionsAppliedProperty)) {
return;
}
var element = View.GetFirstNonGeneratedView(view) as FrameworkElement;
if (element == null) {
return;
}
if (!ShouldApplyConventions(element)) {
Log.Info("Skipping conventions for {0} and {1}.", element, viewModel);
return;
}
var viewModelType = viewModel.GetType();
#if NET45
var viewModelTypeProvider = viewModel as ICustomTypeProvider;
if (viewModelTypeProvider != null) {
viewModelType = viewModelTypeProvider.GetCustomType();
}
#endif
#if XFORMS || MAUI
IEnumerable<FrameworkElement> namedElements = new List<FrameworkElement>();
#else
var namedElements = BindingScope.GetNamedElements(element);
#endif
namedElements = BindActions(namedElements, viewModelType);
namedElements = BindProperties(namedElements, viewModelType);
HandleUnmatchedElements(namedElements, viewModelType);
view.SetValue(ConventionsAppliedProperty, true);
};
}
}