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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace File360.Common
{
/// <summary>
/// NavigationHelper aids in navigation between pages. It provides commands used to
/// navigate back and forward as well as registers for standard mouse and keyboard
/// shortcuts used to go back and forward in Windows and the hardware back button in
/// Windows Phone. In addition it integrates SuspensionManger to handle process lifetime
/// management and state management when navigating between pages.
/// </summary>
/// <example>
/// To make use of NavigationHelper, follow these two steps or
/// start with a BasicPage or any other Page item template other than BlankPage.
///
/// 1) Create an instance of the NavigationHelper somewhere such as in the
/// constructor for the page and register a callback for the LoadState and
/// SaveState events.
/// <code>
/// public MyPage()
/// {
/// this.InitializeComponent();
/// var navigationHelper = new NavigationHelper(this);
/// this.navigationHelper.LoadState += navigationHelper_LoadState;
/// this.navigationHelper.SaveState += navigationHelper_SaveState;
/// }
///
/// private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
/// { }
/// private async void navigationHelper_SaveState(object sender, LoadStateEventArgs e)
/// { }
/// </code>
///
/// 2) Register the page to call into the NavigationHelper whenever the page participates
/// in navigation by overriding the <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedTo"/>
/// and <see cref="Windows.UI.Xaml.Controls.Page.OnNavigatedFrom"/> events.
/// <code>
/// protected override void OnNavigatedTo(NavigationEventArgs e)
/// {
/// navigationHelper.OnNavigatedTo(e);
/// }
///
/// protected override void OnNavigatedFrom(NavigationEventArgs e)
/// {
/// navigationHelper.OnNavigatedFrom(e);
/// }
/// </code>
/// </example>
[Windows.Foundation.Metadata.WebHostHidden]
public class NavigationHelper : DependencyObject
{
private Page Page { get; set; }
private Frame Frame { get { return this.Page.Frame; } }
/// <summary>
/// Initializes a new instance of the <see cref="NavigationHelper"/> class.
/// </summary>
/// <param name="page">A reference to the current page used for navigation.
/// This reference allows for frame manipulation and to ensure that keyboard
/// navigation requests only occur when the page is occupying the entire window.</param>
public NavigationHelper(Page page)
{
this.Page = page;
// When this page is part of the visual tree make two changes:
// 1) Map application view state to visual state for the page
// 2) Handle hardware navigation requests
this.Page.Loaded += (sender, e) =>
{
#if WINDOWS_PHONE_APP
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
#else
// Keyboard and mouse navigation only apply when occupying the entire window
if (this.Page.ActualHeight == Window.Current.Bounds.Height &&
this.Page.ActualWidth == Window.Current.Bounds.Width)
{
// Listen to the window directly so focus isn't required
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
CoreDispatcher_AcceleratorKeyActivated;
Window.Current.CoreWindow.PointerPressed +=
this.CoreWindow_PointerPressed;
}
#endif
};
// Undo the same changes when the page is no longer visible
this.Page.Unloaded += (sender, e) =>
{
#if WINDOWS_PHONE_APP
Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
#else
Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -=
CoreDispatcher_AcceleratorKeyActivated;
Window.Current.CoreWindow.PointerPressed -=
this.CoreWindow_PointerPressed;
#endif
};
}
#region Navigation support
RelayCommand _goBackCommand;
RelayCommand _goForwardCommand;
/// <summary>
/// <see cref="RelayCommand"/> used to bind to the back Button's Command property
/// for navigating to the most recent item in back navigation history, if a Frame
/// manages its own navigation history.
///
/// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoBack"/>
/// as the Execute Action and <see cref="CanGoBack"/> for CanExecute.
/// </summary>
public RelayCommand GoBackCommand
{
get
{
if (_goBackCommand == null)
{
_goBackCommand = new RelayCommand(
() => this.GoBack(),
() => this.CanGoBack());
}
return _goBackCommand;
}
set
{
_goBackCommand = value;
}
}
/// <summary>
/// <see cref="RelayCommand"/> used for navigating to the most recent item in
/// the forward navigation history, if a Frame manages its own navigation history.
///
/// The <see cref="RelayCommand"/> is set up to use the virtual method <see cref="GoForward"/>
/// as the Execute Action and <see cref="CanGoForward"/> for CanExecute.
/// </summary>
public RelayCommand GoForwardCommand
{
get
{
if (_goForwardCommand == null)
{
_goForwardCommand = new RelayCommand(
() => this.GoForward(),
() => this.CanGoForward());
}
return _goForwardCommand;
}
}
/// <summary>
/// Virtual method used by the <see cref="GoBackCommand"/> property
/// to determine if the <see cref="Frame"/> can go back.
/// </summary>
/// <returns>
/// true if the <see cref="Frame"/> has at least one entry
/// in the back navigation history.
/// </returns>
public virtual bool CanGoBack()
{
return this.Frame != null && this.Frame.CanGoBack;
}
/// <summary>
/// Virtual method used by the <see cref="GoForwardCommand"/> property
/// to determine if the <see cref="Frame"/> can go forward.
/// </summary>
/// <returns>
/// true if the <see cref="Frame"/> has at least one entry
/// in the forward navigation history.
/// </returns>
public virtual bool CanGoForward()
{
return this.Frame != null && this.Frame.CanGoForward;
}
/// <summary>
/// Virtual method used by the <see cref="GoBackCommand"/> property
/// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoBack"/> method.
/// </summary>
public virtual void GoBack()
{
if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
}
/// <summary>
/// Virtual method used by the <see cref="GoForwardCommand"/> property
/// to invoke the <see cref="Windows.UI.Xaml.Controls.Frame.GoForward"/> method.
/// </summary>
public virtual void GoForward()
{
if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward();
}
#if WINDOWS_PHONE_APP
/// <summary>
/// Invoked when the hardware back button is pressed. For Windows Phone only.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
if (this.GoBackCommand.CanExecute(null))
{
e.Handled = true;
this.GoBackCommand.Execute(null);
}
}
#else
/// <summary>
/// Invoked on every keystroke, including system keys such as Alt key combinations, when
/// this page is active and occupies the entire window. Used to detect keyboard navigation
/// between pages even when the page itself doesn't have focus.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender,
AcceleratorKeyEventArgs e)
{
var virtualKey = e.VirtualKey;
// Only investigate further when Left, Right, or the dedicated Previous or Next keys
// are pressed
if ((e.EventType == CoreAcceleratorKeyEventType.SystemKeyDown ||
e.EventType == CoreAcceleratorKeyEventType.KeyDown) &&
(virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right ||
(int)virtualKey == 166 || (int)virtualKey == 167))
{
var coreWindow = Window.Current.CoreWindow;
var downState = CoreVirtualKeyStates.Down;
bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
bool noModifiers = !menuKey && !controlKey && !shiftKey;
bool onlyAlt = menuKey && !controlKey && !shiftKey;
if (((int)virtualKey == 166 && noModifiers) ||
(virtualKey == VirtualKey.Left && onlyAlt))
{
// When the previous key or Alt+Left are pressed navigate back
e.Handled = true;
this.GoBackCommand.Execute(null);
}
else if (((int)virtualKey == 167 && noModifiers) ||
(virtualKey == VirtualKey.Right && onlyAlt))
{
// When the next key or Alt+Right are pressed navigate forward
e.Handled = true;
this.GoForwardCommand.Execute(null);
}
}
}
/// <summary>
/// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
/// page is active and occupies the entire window. Used to detect browser-style next and
/// previous mouse button clicks to navigate between pages.
/// </summary>
/// <param name="sender">Instance that triggered the event.</param>
/// <param name="e">Event data describing the conditions that led to the event.</param>
private void CoreWindow_PointerPressed(CoreWindow sender,
PointerEventArgs e)
{
var properties = e.CurrentPoint.Properties;
// Ignore button chords with the left, right, and middle buttons
if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed ||
properties.IsMiddleButtonPressed) return;
// If back or foward are pressed (but not both) navigate appropriately
bool backPressed = properties.IsXButton1Pressed;
bool forwardPressed = properties.IsXButton2Pressed;
if (backPressed ^ forwardPressed)
{
e.Handled = true;
if (backPressed) this.GoBackCommand.Execute(null);
if (forwardPressed) this.GoForwardCommand.Execute(null);
}
}
#endif
#endregion
#region Process lifetime management
private String _pageKey;
/// <summary>
/// Register this event on the current page to populate the page
/// with content passed during navigation as well as any saved
/// state provided when recreating a page from a prior session.
/// </summary>
public event LoadStateEventHandler LoadState;
/// <summary>
/// Register this event on the current page to preserve
/// state associated with the current page in case the
/// application is suspended or the page is discarded from
/// the navigaqtion cache.
/// </summary>
public event SaveStateEventHandler SaveState;
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// This method calls <see cref="LoadState"/>, where all page specific
/// navigation and process lifetime management logic should be placed.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property provides the group to be displayed.</param>
public void OnNavigatedTo(NavigationEventArgs e)
{
var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
this._pageKey = "Page-" + this.Frame.BackStackDepth;
if (e.NavigationMode == NavigationMode.New)
{
// Clear existing state for forward navigation when adding a new page to the
// navigation stack
var nextPageKey = this._pageKey;
int nextPageIndex = this.Frame.BackStackDepth;
while (frameState.Remove(nextPageKey))
{
nextPageIndex++;
nextPageKey = "Page-" + nextPageIndex;
}
// Pass the navigation parameter to the new page
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, null));
}
}
else
{
// Pass the navigation parameter and preserved page state to the page, using
// the same strategy for loading suspended state and recreating pages discarded
// from cache
if (this.LoadState != null)
{
this.LoadState(this, new LoadStateEventArgs(e.Parameter, (Dictionary<String, Object>)frameState[this._pageKey]));
}
}
}
/// <summary>
/// Invoked when this page will no longer be displayed in a Frame.
/// This method calls <see cref="SaveState"/>, where all page specific
/// navigation and process lifetime management logic should be placed.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property provides the group to be displayed.</param>
public void OnNavigatedFrom(NavigationEventArgs e)
{
var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
var pageState = new Dictionary<String, Object>();
if (this.SaveState != null)
{
this.SaveState(this, new SaveStateEventArgs(pageState));
}
frameState[_pageKey] = pageState;
}
#endregion
}
/// <summary>
/// Represents the method that will handle the <see cref="NavigationHelper.LoadState"/>event
/// </summary>
public delegate void LoadStateEventHandler(object sender, LoadStateEventArgs e);
/// <summary>
/// Represents the method that will handle the <see cref="NavigationHelper.SaveState"/>event
/// </summary>
public delegate void SaveStateEventHandler(object sender, SaveStateEventArgs e);
/// <summary>
/// Class used to hold the event data required when a page attempts to load state.
/// </summary>
public class LoadStateEventArgs : EventArgs
{
/// <summary>
/// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
/// when this page was initially requested.
/// </summary>
public Object NavigationParameter { get; private set; }
/// <summary>
/// A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.
/// </summary>
public Dictionary<string, Object> PageState { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="LoadStateEventArgs"/> class.
/// </summary>
/// <param name="navigationParameter">
/// The parameter value passed to <see cref="Frame.Navigate(Type, Object)"/>
/// when this page was initially requested.
/// </param>
/// <param name="pageState">
/// A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.
/// </param>
public LoadStateEventArgs(Object navigationParameter, Dictionary<string, Object> pageState)
: base()
{
this.NavigationParameter = navigationParameter;
this.PageState = pageState;
}
}
/// <summary>
/// Class used to hold the event data required when a page attempts to save state.
/// </summary>
public class SaveStateEventArgs : EventArgs
{
/// <summary>
/// An empty dictionary to be populated with serializable state.
/// </summary>
public Dictionary<string, Object> PageState { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="SaveStateEventArgs"/> class.
/// </summary>
/// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
public SaveStateEventArgs(Dictionary<string, Object> pageState)
: base()
{
this.PageState = pageState;
}
}
}