Universal Windows Platform – Badges

Badges demonstrates how to display Badges in Windows 10 these are small notifications that appear on the icon for an application either on the Task Bar Icon or Pinned Tile of an Application.

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10, version 1803 (10.0; Build 17134) which is the April 2018 Update and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Core;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using Windows.UI.StartScreen;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

public class Library
{
    private readonly List<string> glyphs = new List<string>
    {
        "number", "activity", "alarm", "attention", "available", "away",
        "busy", "error", "newMessage", "paused", "playing", "unavailable"
    };

    private async Task<string> DialogAsync()
    {
        ComboBox glyph = new ComboBox()
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            Margin = new Thickness(5),
            ItemsSource = glyphs
        };
        glyph.SelectedIndex = 0;
        TextBox number = new TextBox()
        {
            PlaceholderText = "Number",
            Margin = new Thickness(5)
        };
        StackPanel panel = new StackPanel()
        {
            Orientation = Orientation.Vertical
        };
        panel.Children.Add(glyph);
        panel.Children.Add(number);
        ContentDialog dialog = new ContentDialog()
        {
            Title = "Badges",
            PrimaryButtonText = "Update",
            CloseButtonText = "Cancel",
            Content = panel
        };
        ContentDialogResult result = await dialog.ShowAsync();
        if (result == ContentDialogResult.Primary)
        {
            string selected = (string)glyph.SelectedItem;
            return (selected == "number") ? number.Text : selected;
        }
        return null;
    }

    private void UpdateBadge(string value)
    {
        bool isNumber = int.TryParse(value, out int number);
        XmlDocument badge = BadgeUpdateManager.GetTemplateContent(isNumber ?
            BadgeTemplateType.BadgeNumber : BadgeTemplateType.BadgeGlyph);
        XmlNodeList attributes = badge.GetElementsByTagName("badge");
        IXmlNode node = attributes[0].Attributes.GetNamedItem("value");
        node.NodeValue = value;
        BadgeNotification notification = new BadgeNotification(badge);
        BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(notification);
    }

    public async Task<bool> PinAsync()
    {
        bool isPinned = false;
        AppListEntry entry = (await Package.Current.GetAppListEntriesAsync()).FirstOrDefault();
        if (entry != null)
        {
            isPinned = await StartScreenManager.GetDefault().ContainsAppListEntryAsync(entry);
        }
        if (!isPinned)
        {
            isPinned = await StartScreenManager.GetDefault().RequestAddAppListEntryAsync(entry);
        }
        return isPinned;
    }

    public async void Badge()
    {
        string result = await DialogAsync();
        if (result != null)
        {
            UpdateBadge(result);
        }
    }
}

There’s a list of string for the glyphs supported by a Badge, then a Dialog method that has a ComboBox set to those “glyphs” and a TextBox where a number can be entered between 1 and 99 and returns the entered value as a string. The UpdateBadge method takes a string and checks if this is numeric then gets the template for either BadgeNumber or BadgeGlyph based on this value then the “value” is set to the passed in value and a BadgeNotification created from this and passed to the Update method of the BadgeUpdateManager with CreateBadgeUpdaterForApplication.

The PinAsync method determines if the application is pinned to start with the GetAppListEntriesAsync from the Package.Current with ContainsAppListEntryAsync from the StartScreenManager.GetDefault method and if not uses the RequestAddAppListEntryAsync to pin the application to start. The Badge method uses the Dialog method to get the value to use on a Badge and uses the UpdateBadge method with the “result” of the the Dialog.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Name="Pin" Icon="Pin" Label="Pin" Click="Pin_Click"/>
	<AppBarButton Icon="SetTile" Label="Badge" Click="Badge_Click"/>
</CommandBar>

The MainPage has a CommandBar with two AppBarButton Controls, Pin to perform Pin-to-Start and Badge which will show the Dialog to update the Application’s Badge on the Task Bar or Tile

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private async void Pin_Click(object sender, RoutedEventArgs e)
{
	await library.PinAsync();
}

private void Badge_Click(object sender, RoutedEventArgs e)
{
	library.Badge();
}

Below the MainPage() Method an instance of the Library Class is created, then Pin_Click is used to call the PinAsync Method from the Library Class and Badge_Click the Badge Method.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

After the Application has started running you can then select Pin to pin-to-start the Application and then select Badge display a Dialog where you select Number or Glyph from the ComboBox and Number to use if that option has been selected from the ComboBox.

ran-badges

Step 15

The Badge will be displayed in Windows 10 on the TaskBar or the Pinned Tile for the Application.

ran-badges

Step 16

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Badges show how easy it is to use this kind of notification – the majority of examples for this tended to be in Javascript mostly but this shows how straight-forward it is to do it from C# instead and the example is based from the official documentation for updated Badges.

Creative Commons License

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s