This repository has been archived by the owner on May 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathCellControl.cs
486 lines (405 loc) · 12.9 KB
/
CellControl.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using Windows.UI.Input;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Xamarin.Forms.Internals;
using WBrush = Windows.UI.Xaml.Media.Brush;
using WSolidColorBrush = Windows.UI.Xaml.Media.SolidColorBrush;
namespace Xamarin.Forms.Platform.UWP
{
public class CellControl : ContentControl
{
public static readonly DependencyProperty CellProperty = DependencyProperty.Register("Cell", typeof(object), typeof(CellControl),
new PropertyMetadata(null, (o, e) => ((CellControl)o).SetSource((Cell)e.OldValue, (Cell)e.NewValue)));
public static readonly DependencyProperty IsGroupHeaderProperty = DependencyProperty.Register("IsGroupHeader", typeof(bool), typeof(CellControl), null);
internal static readonly BindableProperty MeasuredEstimateProperty = BindableProperty.Create("MeasuredEstimate", typeof(double), typeof(ListView), -1d);
readonly Lazy<ListView> _listView;
readonly PropertyChangedEventHandler _propertyChangedHandler;
WBrush _defaultOnColor;
IList<MenuItem> _contextActions;
Windows.UI.Xaml.DataTemplate _currentTemplate;
bool _isListViewRealized;
object _newValue;
public CellControl()
{
_listView = new Lazy<ListView>(GetListView);
DataContextChanged += OnDataContextChanged;
Loaded += OnLoaded;
Unloaded += OnUnloaded;
_propertyChangedHandler = OnCellPropertyChanged;
}
void OnLoaded(object sender, RoutedEventArgs e)
{
if (Cell == null)
return;
/// 🚀 subscribe topropertychanged
// make sure we do not subscribe twice (because this could happen in SetSource(Cell oldCell, Cell newCell))
Cell.PropertyChanged -= _propertyChangedHandler;
Cell.PropertyChanged += _propertyChangedHandler;
}
void OnUnloaded(object sender, RoutedEventArgs e)
{
if (Cell == null)
return;
Cell.SendDisappearing();
/// 🚀 unsubscribe from propertychanged
Cell.PropertyChanged -= _propertyChangedHandler;
}
public Cell Cell
{
get { return (Cell)GetValue(CellProperty); }
set { SetValue(CellProperty, value); }
}
public bool IsGroupHeader
{
get { return (bool)GetValue(IsGroupHeaderProperty); }
set { SetValue(IsGroupHeaderProperty, value); }
}
protected FrameworkElement CellContent
{
get { return (FrameworkElement)Content; }
}
protected override Windows.Foundation.Size MeasureOverride(Windows.Foundation.Size availableSize)
{
ListView lv = _listView.Value;
// set the Cell now that we have a reference to the ListView, since it will have been skipped
// on DataContextChanged.
if (_newValue != null)
{
SetCell(_newValue);
_newValue = null;
}
if (Content == null)
{
if (lv != null)
{
if (lv.HasUnevenRows)
{
var estimate = (double)lv.GetValue(MeasuredEstimateProperty);
if (estimate > -1)
return new Windows.Foundation.Size(availableSize.Width, estimate);
}
else
{
double rowHeight = lv.RowHeight;
if (rowHeight > -1)
return new Windows.Foundation.Size(availableSize.Width, rowHeight);
}
}
// This needs to return a size with a non-zero height;
// otherwise, it kills virtualization.
return new Windows.Foundation.Size(0, Cell.DefaultCellHeight);
}
// Children still need measure called on them
Windows.Foundation.Size result = base.MeasureOverride(availableSize);
if (lv != null)
{
lv.SetValue(MeasuredEstimateProperty, result.Height);
}
SetDefaultSwitchColor();
return result;
}
ListView GetListView()
{
DependencyObject parent = VisualTreeHelper.GetParent(this);
while (parent != null)
{
var lv = parent as ListViewRenderer;
if (lv != null)
{
_isListViewRealized = true;
return lv.Element;
}
parent = VisualTreeHelper.GetParent(parent);
}
return null;
}
Windows.UI.Xaml.DataTemplate GetTemplate(Cell cell)
{
var renderer = Registrar.Registered.GetHandlerForObject<ICellRenderer>(cell);
return renderer.GetTemplate(cell);
}
void OnCellPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "HasContextActions")
{
SetupContextMenu();
}
else if (e.PropertyName == VisualElement.FlowDirectionProperty.PropertyName)
UpdateFlowDirection(Cell);
else if (e.PropertyName == SwitchCell.OnProperty.PropertyName ||
e.PropertyName == SwitchCell.OnColorProperty.PropertyName)
{
UpdateOnColor();
}
}
void UpdateOnColor()
{
if (!(Cell is SwitchCell switchCell))
return;
var color = switchCell.OnColor == Color.Default
? _defaultOnColor
: new WSolidColorBrush(switchCell.OnColor.ToWindowsColor());
var nativeSwitch = FrameworkElementExtensions.GetFirstDescendant<ToggleSwitch>(this);
// change fill color in switch rectangle
var rects = nativeSwitch.GetDescendantsByName<Windows.UI.Xaml.Shapes.Rectangle>("SwitchKnobBounds");
foreach (var rect in rects)
rect.Fill = color;
// change color in animation on PointerOver
var grid = nativeSwitch.GetFirstDescendant<Windows.UI.Xaml.Controls.Grid>();
var gridVisualStateGroups = Windows.UI.Xaml.VisualStateManager.GetVisualStateGroups(grid);
Windows.UI.Xaml.VisualStateGroup vsGroup = null;
foreach (var visualGroup in gridVisualStateGroups)
{
if (visualGroup.Name == "CommonStates")
{
vsGroup = visualGroup;
break;
}
}
if (vsGroup == null)
return;
Windows.UI.Xaml.VisualState vState = null;
foreach (var visualState in vsGroup.States)
{
if (visualState.Name == "PointerOver")
{
vState = visualState;
break;
}
}
if (vState == null)
return;
var visualStates = vState.Storyboard.Children;
foreach (ObjectAnimationUsingKeyFrames item in visualStates)
{
if ((string)item.GetValue(Storyboard.TargetNameProperty) == "SwitchKnobBounds")
{
item.KeyFrames[0].Value = color;
break;
}
}
}
void SetDefaultSwitchColor()
{
if (_defaultOnColor == null && Cell is SwitchCell)
{
var nativeSwitch = FrameworkElementExtensions.GetFirstDescendant<ToggleSwitch>(this);
var rects = nativeSwitch.GetDescendantsByName<Windows.UI.Xaml.Shapes.Rectangle>("SwitchKnobBounds");
foreach (var rect in rects)
_defaultOnColor = rect.Fill;
UpdateOnColor();
}
}
void OnClick(object sender, PointerRoutedEventArgs e)
{
PointerPoint point = e.GetCurrentPoint(CellContent);
if (point.Properties.PointerUpdateKind != PointerUpdateKind.RightButtonReleased)
return;
OpenContextMenu();
}
void OnContextActionsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var flyout = GetAttachedFlyout();
if (flyout != null)
{
flyout.Items.Clear();
SetupMenuItems(flyout);
}
}
void OnDataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
if (args.NewValue == null)
return;
// We don't want to set the Cell until the ListView is realized, just in case the
// Cell has an ItemTemplate. Instead, we'll store the new data item, and it will be
// set on MeasureOverrideDelegate. However, if the parent is a TableView, we'll already
// have a complete Cell object to work with, so we can move ahead.
if (_isListViewRealized || args.NewValue is Cell)
SetCell(args.NewValue);
else if (args.NewValue != null)
_newValue = args.NewValue;
}
void OnLongTap(object sender, HoldingRoutedEventArgs e)
{
if (e.HoldingState == HoldingState.Started)
OpenContextMenu();
}
/// <summary>
/// To check the context, not just the text.
/// </summary>
MenuFlyout GetAttachedFlyout()
{
if (FlyoutBase.GetAttachedFlyout(CellContent) is MenuFlyout flyout)
{
var actions = Cell.ContextActions;
if (flyout.Items.Count != actions.Count)
return null;
for (int i = 0; i < flyout.Items.Count; i++)
{
if (flyout.Items[i].DataContext != actions[i])
return null;
}
return flyout;
}
return null;
}
void OpenContextMenu()
{
if (GetAttachedFlyout() == null)
{
var flyout = new MenuFlyout();
SetupMenuItems(flyout);
((INotifyCollectionChanged)Cell.ContextActions).CollectionChanged += OnContextActionsChanged;
_contextActions = Cell.ContextActions;
FlyoutBase.SetAttachedFlyout(CellContent, flyout);
}
FlyoutBase.ShowAttachedFlyout(CellContent);
}
void SetCell(object newContext)
{
var cell = newContext as Cell;
if (cell != null)
{
Cell = cell;
return;
}
if (ReferenceEquals(Cell?.BindingContext, newContext))
return;
// If there is a ListView, load the Cell content from the ItemTemplate.
// Otherwise, the given Cell is already a templated Cell from a TableView.
ListView lv = _listView.Value;
if (lv != null)
{
Cell oldCell = Cell;
bool isGroupHeader = IsGroupHeader;
DataTemplate template = isGroupHeader ? lv.GroupHeaderTemplate : lv.ItemTemplate;
object bindingContext = newContext;
bool sameTemplate = false;
if (template is DataTemplateSelector dataTemplateSelector)
{
template = dataTemplateSelector.SelectTemplate(bindingContext, lv);
// 🚀 If there exists an old cell, get its data template and check
// whether the new- and old template matches. In that case, we can recycle it
if (oldCell?.BindingContext != null)
{
DataTemplate oldTemplate = dataTemplateSelector.SelectTemplate(oldCell?.BindingContext, lv);
sameTemplate = oldTemplate == template;
}
}
// Reuse cell
var canReuseCell = Cell != null && sameTemplate;
// 🚀 If we can reuse the cell, just reuse it...
if (canReuseCell)
{
cell = Cell;
}
else if (template != null)
{
cell = template.CreateContent() as Cell;
}
else
{
if (isGroupHeader)
bindingContext = lv.GetDisplayTextFromGroup(bindingContext);
cell = lv.CreateDefaultCell(bindingContext);
}
// A TableView cell should already have its parent,
// but we need to set the parent for a ListView cell.
cell.Parent = lv;
// Set inherited BindingContext after setting the Parent so it won't be wiped out
BindableObject.SetInheritedBindingContext(cell, bindingContext);
// This provides the Group Header styling (e.g., larger font, etc.) when the
// template is loaded later.
cell.SetIsGroupHeader<ItemsView<Cell>, Cell>(isGroupHeader);
}
// 🚀 Only set the cell if it DID change
// Note: The cleanup (SendDisappearing(), etc.) is done by the Cell propertychanged callback so we do not need to do any cleanup ourselves.
if (Cell != cell)
Cell = cell;
// 🚀 Even if the cell did not change, we **must** call SendDisappearing() and SendAppearing()
// because frameworks such as Reactive UI rely on this! (this.WhenActivated())
else if (Cell != null)
{
Cell.SendDisappearing();
Cell.SendAppearing();
}
}
void SetSource(Cell oldCell, Cell newCell)
{
if (oldCell != null)
{
oldCell.PropertyChanged -= _propertyChangedHandler;
oldCell.SendDisappearing();
}
if (newCell != null)
{
newCell.SendAppearing();
UpdateContent(newCell);
UpdateFlowDirection(newCell);
SetupContextMenu();
// 🚀 make sure we do not subscribe twice (OnLoaded!)
newCell.PropertyChanged -= _propertyChangedHandler;
newCell.PropertyChanged += _propertyChangedHandler;
}
}
void SetupContextMenu()
{
if (CellContent == null || Cell == null)
return;
if (!Cell.HasContextActions)
{
CellContent.Holding -= OnLongTap;
CellContent.PointerReleased -= OnClick;
if (_contextActions != null)
{
((INotifyCollectionChanged)_contextActions).CollectionChanged -= OnContextActionsChanged;
_contextActions = null;
}
FlyoutBase.SetAttachedFlyout(CellContent, null);
return;
}
CellContent.PointerReleased += OnClick;
CellContent.Holding += OnLongTap;
}
void SetupMenuItems(MenuFlyout flyout)
{
foreach (MenuItem item in Cell.ContextActions)
{
var flyoutItem = new MenuFlyoutItem();
flyoutItem.SetBinding(MenuFlyoutItem.TextProperty, "Text");
flyoutItem.Command = new MenuItemCommand(item);
flyoutItem.DataContext = item;
flyout.Items.Add(flyoutItem);
}
}
void UpdateContent(Cell newCell)
{
Windows.UI.Xaml.DataTemplate dt = GetTemplate(newCell);
if (dt != _currentTemplate || Content == null)
{
_currentTemplate = dt;
Content = dt.LoadContent();
}
((FrameworkElement)Content).DataContext = newCell;
}
protected override AutomationPeer OnCreateAutomationPeer()
{
return new FrameworkElementAutomationPeer(this);
}
void UpdateFlowDirection(Cell newCell)
{
if (newCell is ViewCell)
return;
this.UpdateFlowDirection(newCell.Parent as VisualElement);
}
}
}