In this article I will show how to display local toast notifications in Universal Windows Apps. No backend is required to display local toasts. It can be triggered to show completion of some event or notify about some error in the task being executed.
Step 1: Setup the UI of your page to Trigger a Local Toast
We add a TextBox and Button on our page. On clicking the Button, TextBox’s Text will be displayed as a local Toast. We are keeping the MainPage.xaml in the Shared project itself as the UI for both Windows Phone and Windows app will be common for our sample project.
Step 2: Add a Toast Service class in the Shared project
We create a new
ToastService class and add a static method
ShowToastNotification which takes a string argument
message to it.
This method is responsible for the following:
- Set toast’s text to the message passed as argument
- Set image source to some hardcoded value
- Set toast’s duration. In our sample we are setting the duration to short.
- Set toast’s navigation. This is the NavigationUri string which can be handled by the app to navigate to a particular page when the notification is tapped. Arguments can also be passed to it.
- Create the toast notification based on the XML content you’ve specified.
- Show the toast notification
Step 3: Add a Click event handler to trigger local toast
Add a click event handler for the Button to trigger a local toast to be displayed. In the code behind for the click event, the
ShowToastNotification method is called with the TextBox’s text passed as an argument.
Here’s how the toast notification appears in the action center.
Feel free to download the full project’s source code or clone it from GitHub.