January 2017

Volume 32 Number 1

[Modern Apps]

Exploring the UWP Community Toolkit

By Frank La | January 2017

Frank La VigneAs the Universal Windows Platform (UWP) evolves, common UI patterns and challenges emerge. While the UWP provides a rich feature set of controls and APIs out of the box, there are some gaps in what’s provided and some features require a lot of coding and effort. To address this gap and make UWP development faster and more accessible to beginners, Microsoft has created the UWP Community Toolkit and placed it on GitHub (bit.ly/2b1PAJY).

The goal of the UWP Community Toolkit is to engage the developer community to create a series of controls and helper functions to simplify UWP development. The UWP Community Toolkit has five categories of tools: Controls, Notifications, Animations, Services and Helpers. In this month’s column, I’ll walk through each of the categories and demonstrate how to implement the toolkit into your UWP projects.

UWP Community Toolkit Sample App

The best way to explore the UWP Community Toolkit is to download the UWP Community Toolkit Sample App from the Windows Store (bit.ly/2bypOyw). Not only does the app showcase all of the features of the toolkit (see Figure 1), but it also provides interactive demos of controls, animations, notifications and more, as shown in Figure 2.

Home Screen of the UWP Community Toolkit Sample App
Figure 1 Home Screen of the UWP Community Toolkit Sample App

Adjusting the Parameters of the RadialGauge Control
Figure 2 Adjusting the Parameters of the RadialGauge Control

The app will also provide XAML and code representations of the controls, thereby making it faster to tinker, tweak, and implement UI elements.

Interface Controls As previously stated, the UWP Community Toolkit contains a number of UI controls: 13 at press time. Many of these controls are commonly found in mobile applications or Web sites optimized for mobile. One such example is the HamburgerMenu control. By convention, the hamburger menu, which consists of three horizontal lines, indicates that there’s a collapsed menu. Touching or clicking on the control toggles its state. Figure 3 and Figure 4 demonstrate what the control looks like collapsed and expanded, respectively.  

A Collapsed Hamburger Menu
Figure 3 A Collapsed Hamburger Menu

An Expanded Hamburger Menu
Figure 4 An Expanded Hamburger Menu

Be sure to explore the features and settings of every control in the UWP Community Toolkit. They have an enormous degree of flexibility and are sure to add value to every one of your UWP projects.

Notifications Windows 10 provides a rich API that lets developers create live tiles and toast notifications to alert users of timely events and keep users up-to-date. For a full exploration of tiles and toast notifications, I recommend reading the Tiles and Toasts blog that’s written by the team that owns the UWP tile and toast APIs (bit.ly/2fzFsv1).

While useful and powerful, creating notifications and live tiles can prove challenging to developers unfamiliar with XML and XPath. The UWP Community Toolkit makes this easier by placing an object model on top of the underlying structure to generate the UI for toasts notifications and live tiles.

Animations Windows 10 introduced the Composition API, a rich, declarative, retained-mode API that any UWP app can use to create composition objects, animations and visual effects directly. Essentially, it’s a layer between XAML and the underlying DirectX architecture. The Composition API is meant to provide a way for XAML developers to enjoy many of the performance benefits of DirectX while writing code in C#. A full discussion of the Composition API is beyond the scope of this column, but you can find out more at bit.ly/2fzCfeQ.

The UWP Community Toolkit provides easy access to the power of this API by providing both XAML behaviors and extension methods on top of the Composition API. The UWP Community Toolkit Sample App even has a control surface to experiment with different parameters on a set of five animations. The toolkit will even generate the C# code and XAML markup to implement the animation.

Services We live in an era of the cloud and apps are better when they’re connected to services in the cloud. However, adding these services to your apps can introduce a lot of complexity: implementing authentication via OAuth, working with REST APIs and the fluid nature of these APIs. Fortunately, the UWP Community Toolkit provides an extensive object model that deals with a lot of this complexity. Currently, the UWP Toolkit provides support for Bing, LinkedIn, Facebook, Twitter and the Microsoft Graph Service. This means that developers can easily connect to these online services with minimal effort.

Helper Functions The UWP Community Toolkit also includes various helper functions to make common app development tasks easier. For instance, before querying a cloud service, apps should check to see if there’s a network connection. While that can be done without this toolkit, it can be done only in one line of code with the toolkit. Helpers are also available for printing, background tasks, obtaining system information and more.

Adding the UWP Community Toolkit to Your Project

The best way to add the UWP Community Toolkit to your project is through NuGet. Create a new blank UWP project in Visual Studio by choosing New Project from the File menu. Select Installed | Templates | Windows | Universal | Blank App (Universal Windows). Name the project UWPToolKitApp and then click OK.

The easiest way to add the UWP Community Toolkit to your project is to add the NuGet packages. In Solution Explorer, right-click on References and choose Manage NuGet Packages from the context menu to show the NuGet Package Manager.

In the search box, type Microsoft.Toolkit.Uwp to bring up all the NuGet packages associated with the UWP Community Toolkit. You should see a handful of results that include the UWP Community Toolkit itself, plus other packages and libraries. For a quick reference chart on which packages contain which functionality, refer to Figure 5

Figure 5 UWP Community Toolkit NuGet Packages

NuGet Package Name Details
Microsoft.Toolkit.Uwp Main NuGet package includes code-only helpers such as Colors conversion tool, Internet Connection detection, Storage file handling, a Stream helper class and so on.
Microsoft.Toolkit.Uwp.Notifications Notifications Package—Generate tile, toast and badge notifications for Windows 10 via code. Includes IntelliSense support to avoid having to use the XML syntax.
Microsoft.Toolkit.Uwp.Notifications.Javascript Notification Packages for JavaScript.
Microsoft.Toolkit.Uwp.Services Services Package—this NuGet package includes the service helpers for Bing, Facebook, LinkedIn, Microsoft Graph and Twitter.
Microsoft.Toolkit.Uwp.UI UI Packages—XAML converters, Visual tree extensions and helpers for your XAML UI.
Microsoft.Toolkit.Uwp.UI.Animations Animations and Composition behaviors such as Blur, Fade, Rotate and so on.
Microsoft.Toolkit.Uwp.UI.Controls XAML Controls such as RadialGauge, RangeSelector and so on.

For now, you’ll want to add the main NuGet Package (Microsoft.Toolkit.Uwp) and the Services package (Microsoft.Toolkit.Uwp.Services). Click on the entry for Microsoft.Toolkit.Uwp and then on the Install button that appears toward the right side of the NuGet Package Manager. If prompted with a Review Changes dialog, review the changes and then click OK. Clicking Cancel here will cancel the NuGet Package install. You might also be shown a License Acceptance dialog; click I Accept to accept the license terms.  You have an option to review the license. You also have the option to decline the license. Clicking I Accept will complete the package install. Repeat the process for the Microsoft.Toolkit.Uwp.Services package, which might have multiple license terms to accept.

Once these tasks are completed, you should see the NuGet packages in the References section of your project in Solution Explorer.

Searching with Bing Now, you’re going to create a sample app that will check for online connectivity and the device model on which the app is running. It will then present you the option to search Bing for information about that device.

Open the MainPage.xaml file and add the XAML in Figure 6 to create a simple UI.

Figure 6 XAML to Create the Sample App’s UI

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
  <Grid.RowDefinitions>
    <RowDefinition Height="33*"/>
    <RowDefinition Height="607*"/>
  </Grid.RowDefinitions>
  <Button Name="btnSearch" Click="btnSearch_Click" Grid.Row="0">Search Bing</Button>
  <ListView Name="lvSearchResults" Grid.Row="1">
    <ListView.ItemTemplate>
      <DataTemplate>
        <StackPanel>
          <TextBlock Text="{Binding Title}" FontWeight="Bold"></TextBlock>
          <TextBlock Text="{Binding Published}" FontStyle="Italic" ></TextBlock>
          <TextBlock Text="{Binding Link}" Foreground="Blue"></TextBlock>
          <TextBlock Text="{Binding Summary}"></TextBlock>
        </StackPanel>
      </DataTemplate>
   </ListView.ItemTemplate>
  </ListView>
</Grid>

In the MainPage.xaml.cs file, add the following code to the constructor method:

btnSearch.IsEnabled = ConnectionHelper.IsInternetAvailable;
btnSearch.Content = $"Search Bing for {SystemInformation.DeviceModel}";

And add the following code to the MainPage.xaml.cs file:

private async void btnSearch_Click(object sender, RoutedEventArgs e)
  {
    var searchConfig = new BingSearchConfig
    {
      Country = BingCountry.UnitedStates,
      Language = BingLanguage.English,
      Query = SystemInformation.DeviceModel,
      QueryType = BingQueryType.Search
    };
  lvSearchResults.ItemsSource =
    await BingService.Instance.RequestAsync(searchConfig, 50);
  }

Visual Studio will help you add the appropriate using statements to your code.

Run the solution now. If your device has Internet connectivity, then the Search button should be enabled. You’ll also see the device model in the button text. If the button is enabled, click on it and you’ll see something similar to Figure 7. Naturally, the specific results vary based on the device the app runs on.

Search Results for Device Model
Figure 7 Search Results for Device Model

Toast Notifications Another feature of the UWP Community Toolkit that simplifies common developer tasks is toast notifications. Toast notifications are an important part of the UX in UWP apps, because they keep users informed as to the state of the app. However, the Toast Notification API requires thorough knowledge of XML. This can confuse novice-level developers and even frustrate more seasoned ones. The UWP Community Toolkit really simplifies creating toast notifications.

For the sample app, you’ll add a simple toast notification to inform the user that the search results have returned. This might not add much value to the sample app, as Bing returns results instantly. However, this would be useful in alerting the user to the completion of a long-running task.

The first step is to add the Microsoft.Toolkit.Uwp.Notifications NuGet package to the project. Repeat the steps mentioned earlier to add it to the project. 

Next, add the code in Figure 8 to the MainPage.xaml.cs file to create the content of the Toast notification. It uses the System Information helper class to fill in some details about the device on which  the app is running.

Figure 8 Code to Create Sample Toast Notification Content

private ToastContent CreateDummyToast()
{
  return new ToastContent()
  {
    Launch = "action=viewEvent&eventId=1983",
    Scenario = ToastScenario.Default,
    Visual = new ToastVisual()
    {
      BindingGeneric = new ToastBindingGeneric()
        {
          Children =
            {
              new AdaptiveText()
                {Text = $"Bing search results returned for
                  {SystemInformation.DeviceModel}"},
              new AdaptiveText()
                {Text = $"Available Memory {SystemInformation.AvailableMemory}"},
              new AdaptiveText(){Text =
                $"Running {SystemInformation.OperatingSystem}
                {SystemInformation.OperatingSystemVersion}
                ({SystemInformation.OperatingSystemArchitecture})"}
             }
          }
        }
      };
    }

Looking at the code more closely, you’ll see that the UWP Community Toolkit adds an object model around the Toast Notification API XML format. This simplifies the process of creating content for the toast notification. Developers can enjoy the power and flexibility of the open-ended format while getting an object model (and IntelliSense) to write code against.

Now, add the following method:

private void PopToast()
{
  ToastContent toastContent = CreateDummyToast();
  ToastNotificationManager.CreateToastNotifier()
    .Show(new ToastNotification(toastContent.GetXml()));
}

The first line calls the CreateDummyToast method that builds the content of the toast notification and assigns it to a ToastContent object. The second line uses the GetXml method to convert the object model to the XML format that the Toast Notification API expects. 

All that’s left to do now is call the PopToast method right after the search results return from Bing in the btnSearch_Click event handler. Run the solution and, just as before, click on the Search button. Almost immediately, you’ll see a notification similar to Figure 9 appear.

Toast Notification Returned
Figure 9 Toast Notification Returned

Wrapping Up

The UWP Community Toolkit provides essential resources for creating rich and engaging UWP apps. From new controls to cloud services API libraries, it enables developers to easily create apps that are connected to services in the cloud without having to deal with lower-level plumbing concerns of REST APIs. Best of all, thanks to the community of developers contributing to it, the UWP Community Toolkit is getting better all the time. The feature set is continually growing and the team is accepting contributions. It’s truly something created for the community by the community.


Frank La Vigne is an independent consultant, where he helps customers leverage technology in order to create a better community. He blogs regularly at FranksWorld.com and has a YouTube channel called Frank's World TV (FranksWorld.TV).

Thanks to the following technical experts for reviewing this article: David Catuhe


Discuss this article in the MSDN Magazine forum