Skip to content
This repository was archived by the owner on Dec 31, 2019. It is now read-only.

Guide: Creating an App Wide LocalNotificationManager

яανιη∂υ ℓιγαηαρατнιяαηα edited this page Aug 6, 2017 · 6 revisions

This guide is about instantiating a LocalNotificationManager that is accessible, and able to display notifications throughout your Universal Windows application.

The code being modified is that of a new blank Universal Windows application within Visual Studio, with comments and irrelavant lines of code redacted for brevity.

By default, the App class that derives from the Application class is the starting point of a Universal Windows application. Among its numerous responsibilities is the creation of the Frame within which the contents of the application are displayed, for which the default implementation contained within the OnLaunched override contained within App.xaml.cs is,

Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null)
{
	rootFrame = new Frame();

	// ...

	Window.Current.Content = rootFrame;
}

Accordingly, a frame identified as rootFrame is created and assigned as the content of the current window.

To create an app-wide notification manager, rootFrame has to be placed within a Grid (identified as rootGrid), which will contain yet another grid (identified as notificationGrid), placed above rootFrame, which will be used for displaying local notifications, creating a layout equivalent to the following XAML markup,

<Grid x:Name="rootGrid">
	<Frame x:Name="rootFrame" />
	<Grid x:Name="notificationGrid" />
</Grid>

An instance of the LocalNotificationManager class (identified as manager) can then be created in App.xaml.cs in a way in which it is accessible in the necessary scope. Accordingly, the relavant OnLaunched code will be transformed to the following,

Grid rootGrid = Window.Current.Content as Grid;
Frame rootFrame = rootGrid?.Children.Where((c) => c is Frame).Cast<Frame>().FirstOrDefault();

if (rootGrid == null)
{
	rootGrid = new Grid();
	rootFrame = new Frame();
	var notificationGrid = new Grid();
	
	manager = new LocalNotificationManager(notificationGrid);

	rootGrid.Children.Add(rootFrame);
	rootGrid.Children.Add(notificationGrid);
	
	// ...

	Window.Current.Content = rootGrid;
}

As for the accessibility of manager, either define it as a static member to be accessed as App.manager,

sealed partial class App : Application
{
	public static LocalNotificationManager manager;

	// ...

or as an instance member accessed as App.Current.manager.

sealed partial class App : Application
{
	// By default, current is an instance of the Application class, which needs to be changed to be an instance of the App class.
	public static new App Current;

	public LocalNotificationManager manager;
	
	public App()
	{
		Current = this;
		// ...

Note that App.xaml.cs of the demonstrative application contains the same implementation.

Clone this wiki locally