-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
MasterDetailsView.cs
584 lines (520 loc) · 22.2 KB
/
MasterDetailsView.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Toolkit.Uwp.UI.Extensions;
using Windows.ApplicationModel;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
namespace Microsoft.Toolkit.Uwp.UI.Controls
{
/// <summary>
/// Panel that allows for a Master/Details pattern.
/// </summary>
[TemplatePart(Name = PartDetailsPresenter, Type = typeof(ContentPresenter))]
[TemplatePart(Name = PartDetailsPanel, Type = typeof(FrameworkElement))]
[TemplateVisualState(Name = NoSelectionNarrowState, GroupName = SelectionStates)]
[TemplateVisualState(Name = NoSelectionWideState, GroupName = SelectionStates)]
[TemplateVisualState(Name = HasSelectionWideState, GroupName = SelectionStates)]
[TemplateVisualState(Name = HasSelectionNarrowState, GroupName = SelectionStates)]
[TemplateVisualState(Name = NarrowState, GroupName = WidthStates)]
[TemplateVisualState(Name = WideState, GroupName = WidthStates)]
public partial class MasterDetailsView : ItemsControl
{
private const string PartDetailsPresenter = "DetailsPresenter";
private const string PartDetailsPanel = "DetailsPanel";
private const string PartBackButton = "MasterDetailsBackButton";
private const string PartHeaderContentPresenter = "HeaderContentPresenter";
private const string NarrowState = "NarrowState";
private const string WideState = "WideState";
private const string WidthStates = "WidthStates";
private const string SelectionStates = "SelectionStates";
private const string HasSelectionNarrowState = "HasSelectionNarrow";
private const string HasSelectionWideState = "HasSelectionWide";
private const string NoSelectionNarrowState = "NoSelectionNarrow";
private const string NoSelectionWideState = "NoSelectionWide";
private AppViewBackButtonVisibility? _previousSystemBackButtonVisibility;
private bool _previousNavigationViewBackEnabled;
// Int used because the underlying type is an enum, but we don't have access to the enum
private int _previousNavigationViewBackVisibilty;
private ContentPresenter _detailsPresenter;
private VisualStateGroup _selectionStateGroup;
private Button _inlineBackButton;
private object _navigationView;
private Frame _frame;
/// <summary>
/// Initializes a new instance of the <see cref="MasterDetailsView"/> class.
/// </summary>
public MasterDetailsView()
{
DefaultStyleKey = typeof(MasterDetailsView);
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}
/// <summary>
/// Invoked whenever application code or internal processes (such as a rebuilding layout pass) call
/// ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays
/// in your app. Override this method to influence the default post-template logic of a class.
/// </summary>
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (_inlineBackButton != null)
{
_inlineBackButton.Click -= OnInlineBackButtonClicked;
}
_inlineBackButton = (Button)GetTemplateChild(PartBackButton);
if (_inlineBackButton != null)
{
_inlineBackButton.Click += OnInlineBackButtonClicked;
}
_detailsPresenter = (ContentPresenter)GetTemplateChild(PartDetailsPresenter);
SetDetailsContent();
SetMasterHeaderVisibility();
OnDetailsCommandBarChanged();
OnMasterCommandBarChanged();
SizeChanged -= MasterDetailsView_SizeChanged;
SizeChanged += MasterDetailsView_SizeChanged;
UpdateView(true);
}
/// <summary>
/// Fired when the SelectedIndex changes.
/// </summary>
/// <param name="d">The sender</param>
/// <param name="e">The event args</param>
/// <remarks>
/// Sets up animations for the DetailsPresenter for animating in/out.
/// </remarks>
private static void OnSelectedIndexChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = (MasterDetailsView)d;
var newValue = (int)e.NewValue < 0 ? null : view.Items[(int)e.NewValue];
var oldValue = e.OldValue == null ? null : view.Items.ElementAtOrDefault((int)e.OldValue);
// check if selection actually changed
if (view.SelectedItem != newValue)
{
// sync SelectedItem
view.SetValue(SelectedItemProperty, newValue);
view.UpdateSelection(oldValue, newValue);
}
}
/// <summary>
/// Fired when the SelectedItem changes.
/// </summary>
/// <param name="d">The sender</param>
/// <param name="e">The event args</param>
/// <remarks>
/// Sets up animations for the DetailsPresenter for animating in/out.
/// </remarks>
private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = (MasterDetailsView)d;
var index = e.NewValue == null ? -1 : view.Items.IndexOf(e.NewValue);
// check if selection actually changed
if (view.SelectedIndex != index)
{
// sync SelectedIndex
view.SetValue(SelectedIndexProperty, index);
view.UpdateSelection(e.OldValue, e.NewValue);
}
}
/// <summary>
/// Fired when the <see cref="MasterHeader"/> is changed.
/// </summary>
/// <param name="d">The sender</param>
/// <param name="e">The event args</param>
private static void OnMasterHeaderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = (MasterDetailsView)d;
view.SetMasterHeaderVisibility();
}
/// <summary>
/// Fired when the DetailsCommandBar changes.
/// </summary>
/// <param name="d">The sender</param>
/// <param name="e">The event args</param>
private static void OnDetailsCommandBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = (MasterDetailsView)d;
view.OnDetailsCommandBarChanged();
}
/// <summary>
/// Fired when CompactModeThresholdWIdthChanged
/// </summary>
/// <param name="d">The sender</param>
/// <param name="e">The event args</param>
private static void OnCompactModeThresholdWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((MasterDetailsView)d).HandleStateChanges();
}
private static void OnBackButtonBehaviorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = (MasterDetailsView)d;
view.SetBackButtonVisibility();
}
/// <summary>
/// Fired when the MasterCommandBar changes.
/// </summary>
/// <param name="d">The sender</param>
/// <param name="e">The event args</param>
private static void OnMasterCommandBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var view = (MasterDetailsView)d;
view.OnMasterCommandBarChanged();
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (DesignMode.DesignModeEnabled == false)
{
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
if (_frame != null)
{
_frame.Navigating -= OnFrameNavigating;
}
_navigationView = this.FindAscendants().FirstOrDefault(p => p.GetType().FullName == "Microsoft.UI.Xaml.Controls.NavigationView");
_frame = this.FindAscendant<Frame>();
if (_frame != null)
{
_frame.Navigating += OnFrameNavigating;
}
_selectionStateGroup = (VisualStateGroup)GetTemplateChild(SelectionStates);
if (_selectionStateGroup != null)
{
_selectionStateGroup.CurrentStateChanged += OnSelectionStateChanged;
}
UpdateView(true);
}
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
if (DesignMode.DesignModeEnabled == false)
{
SystemNavigationManager.GetForCurrentView().BackRequested -= OnBackRequested;
if (_frame != null)
{
_frame.Navigating -= OnFrameNavigating;
}
_selectionStateGroup = (VisualStateGroup)GetTemplateChild(SelectionStates);
if (_selectionStateGroup != null)
{
_selectionStateGroup.CurrentStateChanged -= OnSelectionStateChanged;
_selectionStateGroup = null;
}
}
}
private void MasterDetailsView_SizeChanged(object sender, SizeChangedEventArgs e)
{
// if size is changing
if ((e.PreviousSize.Width < CompactModeThresholdWidth && e.NewSize.Width >= CompactModeThresholdWidth) ||
(e.PreviousSize.Width >= CompactModeThresholdWidth && e.NewSize.Width < CompactModeThresholdWidth))
{
HandleStateChanges();
}
}
private void OnInlineBackButtonClicked(object sender, RoutedEventArgs e)
{
SelectedItem = null;
}
/// <summary>
/// Raises SelectionChanged event and updates view.
/// </summary>
/// <param name="oldSelection">Old selection.</param>
/// <param name="newSelection">New selection.</param>
private void UpdateSelection(object oldSelection, object newSelection)
{
OnSelectionChanged(new SelectionChangedEventArgs(new List<object> { oldSelection }, new List<object> { newSelection }));
UpdateView(true);
// If there is no selection, do not remove the DetailsPresenter content but let it animate out.
if (SelectedItem != null)
{
SetDetailsContent();
}
}
private void HandleStateChanges()
{
UpdateView(true);
SetListSelectionWithKeyboardFocusOnVisualStateChanged(ViewState);
}
/// <summary>
/// Closes the details pane if we are in narrow state
/// </summary>
/// <param name="sender">The sender</param>
/// <param name="args">The event args</param>
private void OnFrameNavigating(object sender, NavigatingCancelEventArgs args)
{
if ((args.NavigationMode == NavigationMode.Back) && (ViewState == MasterDetailsViewState.Details))
{
SelectedItem = null;
args.Cancel = true;
}
}
/// <summary>
/// Closes the details pane if we are in narrow state
/// </summary>
/// <param name="sender">The sender</param>
/// <param name="args">The event args</param>
private void OnBackRequested(object sender, BackRequestedEventArgs args)
{
if (ViewState == MasterDetailsViewState.Details)
{
// let the OnFrameNavigating method handle it if
if (_frame == null || !_frame.CanGoBack)
{
SelectedItem = null;
}
args.Handled = true;
}
}
private void SetMasterHeaderVisibility()
{
if (GetTemplateChild(PartHeaderContentPresenter) is FrameworkElement headerPresenter)
{
headerPresenter.Visibility = MasterHeader != null
? Visibility.Visible
: Visibility.Collapsed;
}
}
private void UpdateView(bool animate)
{
UpdateViewState();
SetVisualState(animate);
}
/// <summary>
/// Sets the back button visibility based on the current visual state and selected item
/// </summary>
private void SetBackButtonVisibility(MasterDetailsViewState? previousState = null)
{
const int backButtonVisible = 1;
if (DesignMode.DesignModeEnabled)
{
return;
}
if (ViewState == MasterDetailsViewState.Details)
{
if ((BackButtonBehavior == BackButtonBehavior.Inline) && (_inlineBackButton != null))
{
_inlineBackButton.Visibility = Visibility.Visible;
}
else if (BackButtonBehavior == BackButtonBehavior.Automatic)
{
// Continue to support the system back button if it is being used
var navigationManager = SystemNavigationManager.GetForCurrentView();
if (navigationManager.AppViewBackButtonVisibility == AppViewBackButtonVisibility.Visible)
{
// Setting this indicates that the system back button is being used
_previousSystemBackButtonVisibility = navigationManager.AppViewBackButtonVisibility;
}
else if ((_inlineBackButton != null) && ((_navigationView == null) || (_frame == null)))
{
// We can only use the new NavigationView if we also have a Frame
// If there is no frame we have to use the inline button
_inlineBackButton.Visibility = Visibility.Visible;
}
else
{
SetNavigationViewBackButtonState(backButtonVisible, true);
}
}
else if (BackButtonBehavior != BackButtonBehavior.Manual)
{
var navigationManager = SystemNavigationManager.GetForCurrentView();
_previousSystemBackButtonVisibility = navigationManager.AppViewBackButtonVisibility;
navigationManager.AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
}
}
else if (previousState == MasterDetailsViewState.Details)
{
if ((BackButtonBehavior == BackButtonBehavior.Inline) && (_inlineBackButton != null))
{
_inlineBackButton.Visibility = Visibility.Collapsed;
}
else if (BackButtonBehavior == BackButtonBehavior.Automatic)
{
if (_previousSystemBackButtonVisibility.HasValue == false)
{
if ((_inlineBackButton != null) && ((_navigationView == null) || (_frame == null)))
{
_inlineBackButton.Visibility = Visibility.Collapsed;
}
else
{
SetNavigationViewBackButtonState(_previousNavigationViewBackVisibilty, _previousNavigationViewBackEnabled);
}
}
}
if (_previousSystemBackButtonVisibility.HasValue)
{
// Make sure we show the back button if the stack can navigate back
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = _previousSystemBackButtonVisibility.Value;
_previousSystemBackButtonVisibility = null;
}
}
}
private void UpdateViewState()
{
var previousState = ViewState;
if (ActualWidth < CompactModeThresholdWidth)
{
ViewState = SelectedItem == null ? MasterDetailsViewState.Master : MasterDetailsViewState.Details;
}
else
{
ViewState = MasterDetailsViewState.Both;
}
if (previousState != ViewState)
{
ViewStateChanged?.Invoke(this, ViewState);
SetBackButtonVisibility(previousState);
}
}
private void SetVisualState(bool animate)
{
string state;
string noSelectionState;
string hasSelectionState;
if (ActualWidth < CompactModeThresholdWidth)
{
state = NarrowState;
noSelectionState = NoSelectionNarrowState;
hasSelectionState = HasSelectionNarrowState;
}
else
{
state = WideState;
noSelectionState = NoSelectionWideState;
hasSelectionState = HasSelectionWideState;
}
VisualStateManager.GoToState(this, state, animate);
VisualStateManager.GoToState(this, SelectedItem == null ? noSelectionState : hasSelectionState, animate);
}
private void SetNavigationViewBackButtonState(int visible, bool enabled)
{
if (_navigationView == null)
{
return;
}
var navType = _navigationView.GetType();
var visibleProperty = navType.GetProperty("IsBackButtonVisible");
if (visibleProperty != null)
{
_previousNavigationViewBackVisibilty = (int)visibleProperty.GetValue(_navigationView);
visibleProperty.SetValue(_navigationView, visible);
}
var enabledProperty = navType.GetProperty("IsBackEnabled");
if (enabledProperty != null)
{
_previousNavigationViewBackEnabled = (bool)enabledProperty.GetValue(_navigationView);
enabledProperty.SetValue(_navigationView, enabled);
}
}
private void SetDetailsContent()
{
if (_detailsPresenter != null)
{
_detailsPresenter.Content = MapDetails == null
? SelectedItem
: SelectedItem != null ? MapDetails(SelectedItem) : null;
}
}
private void OnMasterCommandBarChanged()
{
OnCommandBarChanged("MasterCommandBarPanel", MasterCommandBar);
}
private void OnDetailsCommandBarChanged()
{
OnCommandBarChanged("DetailsCommandBarPanel", DetailsCommandBar);
}
private void OnCommandBarChanged(string panelName, CommandBar commandbar)
{
var panel = GetTemplateChild(panelName) as Panel;
if (panel == null)
{
return;
}
panel.Children.Clear();
if (commandbar != null)
{
panel.Children.Add(commandbar);
}
}
/// <summary>
/// Sets whether the selected item should change when focused with the keyboard based on the view state
/// </summary>
/// <param name="viewState">the view state</param>
private void SetListSelectionWithKeyboardFocusOnVisualStateChanged(MasterDetailsViewState viewState)
{
if (viewState == MasterDetailsViewState.Both)
{
SetListSelectionWithKeyboardFocus(true);
}
else
{
SetListSelectionWithKeyboardFocus(false);
}
}
/// <summary>
/// Sets whether the selected item should change when focused with the keyboard
/// </summary>
private void SetListSelectionWithKeyboardFocus(bool singleSelectionFollowsFocus)
{
if (GetTemplateChild("MasterList") is Windows.UI.Xaml.Controls.ListViewBase masterList)
{
masterList.SingleSelectionFollowsFocus = singleSelectionFollowsFocus;
}
}
/// <summary>
/// Fires when the selection state of the control changes
/// </summary>
/// <param name="sender">the sender</param>
/// <param name="e">the event args</param>
/// <remarks>
/// Sets focus to the item list when the viewState is not Details.
/// Sets whether the selected item should change when focused with the keyboard.
/// </remarks>
private void OnSelectionStateChanged(object sender, VisualStateChangedEventArgs e)
{
SetFocus(ViewState);
SetListSelectionWithKeyboardFocusOnVisualStateChanged(ViewState);
}
/// <summary>
/// Sets focus to the relevant control based on the viewState.
/// </summary>
/// <param name="viewState">the view state</param>
private void SetFocus(MasterDetailsViewState viewState)
{
if (viewState != MasterDetailsViewState.Details)
{
FocusItemList();
}
else
{
FocusFirstFocusableElementInDetails();
}
}
/// <summary>
/// Sets focus to the first focusable element in the details template
/// </summary>
private void FocusFirstFocusableElementInDetails()
{
if (GetTemplateChild(PartDetailsPanel) is DependencyObject details)
{
var focusableElement = FocusManager.FindFirstFocusableElement(details);
(focusableElement as Control)?.Focus(FocusState.Programmatic);
}
}
/// <summary>
/// Sets focus to the item list
/// </summary>
private void FocusItemList()
{
if (GetTemplateChild("MasterList") is Control masterList)
{
masterList.Focus(FocusState.Programmatic);
}
}
}
}