October 20th, 2021

Building Your First UWP Application

Zachary Teutsch
Software Engineer

What’s the deal with UWP?

Universal Windows Platform is all about developing apps that are not only for Windows, but look, feel, and interact like they should be on Windows. Any device that runs Windows can run a UWP application, and UWP allows for integration and styling that really makes your application feel like it belongs on Windows.

One of my favorite UWP applications is Ambie, an open source, white-noise sound application built by one of my colleagues, Daniel Paulino:

Ambie is an awesome app, so let’s try to imitate it!

UWP Animal Soundboard

What if instead of soothing atmospheric noises and a level of iterative polish, Ambie had obnoxious animal noises and was built in 30 minutes?

As simple as this demo app is, it shows some cool things you can do right away with UWP:

  • Working with different types of media (in our case, audio, but it’s just as easy to get started with video, photo, etc.)
  • Speech Synthesis! Just one example of a neat API included with UWP
  • Simple, easy-to-use, and consistent UI controls, especially if you’re using WinUI
  • Templated/dynamic UI that changes through user interaction. You can add as many monkey buttons as you want to this UI, just keep clicking!

Getting Started

Before we’re ready to crash course through making our soundboard, we have to get a few things set up.

Setting Up Your Development Environment

If you’re not on a Windows 10/11 machine, you can download a VM with an already set up development environment here.

To setup the dev environment on your Windows 10/11 machine, let’s download and set up Visual Studio. You can follow a guide to get set up on Windows here.

Creating a Blank UWP App

Once you have Visual Studio installed, go ahead and launch it. At the start screen, select “Create a new project.”

This will take you to a list of templates, go ahead and search for “UWP” and then select “Blank App (Universal Windows).”

Now go ahead and create your project!

Resources

If you’re brand new to UWP and XAML, I highly recommend checking out this Getting Started With UWP guide. It will walk you through how to get started building UWP applications.

Additionally, you can check out the Github repository for this project. It contains all of the code, split out into different parts and commented thoroughly.

Now, let’s hop into the specifics of how this app was built.

So what makes this soundboard tick?

A Visual Studio UWP application comes with a whole set of files that allows your application to be installed and launched properly from the get go, but for now, you can find all of the code we are covering in just two files:

  • MainPage.xaml: This is a XAML file where we will define all of our UI elements, called “controls”, that will make up the visual layer of our application.
  • MainPage.xaml.cs: This is the C# code-behind file where we will put all the logic that lets us interact with our application.

Together, these two files make up our MainPage class. When you run your app (by clicking the little green arrow at the top of Visual Studio), it will automatically navigate to this page.

Let’s take a look at the core elements that make up the MainPage of our Soundboard app:

First, in MainPage.xaml, we’re using GridView control that will dynamically display our sounds:

<GridView x:Name="SoundView"
    ItemsSource="{x:Bind Sounds}"
    ItemTemplate="{StaticResource SoundTemplate}"
    IsItemClickEnabled="True"
    ItemClick="SoundItemClick"
    SelectionMode="Single"/>

GridView controls have an ItemsSource property that allows us to send it a whole collection of items to display. Our GridView’s ItemSource is bound to an ObservableCollection that’s declared in our code-behind MainPage.xaml.cs file:

public ObservableCollection<SoundItem> Sounds { get; set; }

ObservableCollections are “observable” by the UI, that is, if the collection changes, so will the UI. Awesome! Our ObservableCollection is a collection of SoundItems:

public class SoundItem
{
    public string AudioFilename { get; set; }
    public string PreviewText { get; set; }
    public string TextToSpeech { get; set; }

    public SoundItem(string audio, string prev, string tts)
    {
        this.AudioFilename = audio;
        this.PreviewText = prev;
        this.TextToSpeech = tts;
    }
}

These SoundItem objects store the data that will be consumed by our GridView to display our sound items. But wait, how does it know how to display them? That’s where we provide a DataTemplate to our GridViews ItemTemplate property:

<Page.Resources>
    <DataTemplate x:Key="SoundTemplate" x:DataType="local:SoundItem">
        <Border  Background="White" Height="200" Width="200" Margin="10,10,10,10" CornerRadius="30">
            <TextBlock FontSize="50" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{x:Bind PreviewText}"/>
        </Border>
    </DataTemplate>
</Page.Resources>        

Great, we have the look of our soundboard, but now we need some functionality. Let’s add a click listener function to our GridView’s ItemClick property:

private void SoundItemClick(object sender, ItemClickEventArgs e)
{
    SoundItem currentSoundItem = e.ClickedItem as SoundItem;
    if (this.IsTextToSpeech)
    {
        this.ReadTextToSpeech(currentSoundItem);
    }
    else
    {
        this.PlaySoundItem(currentSoundItem);
    }
}

Our click listener calls two different functions depending on whether or not Text-To-Speech mode is enabled. The first plays audio from a file:

private async void PlaySoundItem(SoundItem sound)
{
    MediaPlayerElement mediaPlayerElement = new MediaPlayerElement();
    Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
    Windows.Storage.StorageFile file = await folder.GetFileAsync(sound.AudioFilename);
    mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(file);
    mediaPlayerElement.MediaPlayer.Play();

}

While the second uses the SpeechSynthesizer API to play some text-to-speech audio:

private async void ReadTextToSpeech(SoundItem sound)
{
    MediaPlayerElement mediaPlayerElement = new MediaPlayerElement();
    var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
    synth.Options.SpeakingRate = .7;
    Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(sound.TextToSpeech);
    mediaPlayerElement.Source = MediaSource.CreateFromStream(stream, stream.ContentType);
    mediaPlayerElement.MediaPlayer.Play();
}

Sweet! That’s the core functionality of our soundboard. You can check out the rest of the code that makes it all come together on the github repository.

Check out the documentation for MediaPlayerElement here and the documentation for SpeechSynthesizer here if you want to play with these APIs a bit more.

Next Steps

Get out there and start building your own Windows apps!

Here are some links to check out with resources on building for UWP:

Thanks for tuning in! Feel free to reach out on my socials linked above if you have any questions.

Author

Zachary Teutsch
Software Engineer

Hey everyone! I'm Zach. I just graduated from university this past year and have since started at Microsoft on the APS Scale and Incubation team. I'm looking forward to engaging with students and new developers about building sweet applications on Windows.

9 comments

Discussion is closed. Login to edit/delete existing comments.

  • Faheem Ahmad

    Dear, author, please clarify whether uwp is dead or just on security updates…. Why not we use .net 6 maui instead or uno platform instead they give fluent ui as well as macos and linux compatibility as well? Or even move to flutter once for all.. because they are making thier own automatic uwp apps or win32 version please explain…

  • MgSam

    According to Paul Thurrott, Microsoft announced yesterday (10/19/2021) that UWP was deprecated. Odd time to publish an article for getting started with UWP.

    • PandaSharp

      People should stop to follow Thurrot, he spread lot of misleading news over the years

    • Fabien Geraud

      You’re post use this link https://github.com/microsoft/WindowsAppSDK/discussions/1615 to prove MS deprecate UWP. This clearly state :

      if you are happy with your current functionality in UWP, there is no need to migrate your project type. WinUI 2.x and the Windows SDK will continue to support UWP project types, including bug, reliability, and security fixes. In Windows, we use UWP project types for several of our own Windows apps.

    • Faheem Ahmad

      Dear, author, please clarify whether uwp is dead or just on security updates…. Why not we use .net 6 maui instead or uno platform instead they give fluent ui as well as macos and linux compatibility as well? Or even move to flutter once for all.. because they are making thier own automatic uwp apps or win32 version please explain

  • Paul Smith

    I’m confused. Why publish a “getting started with UWP” when it’s fairly clear that everything is moving away from UWP?
    Windows App SDK Announcements
    According to this, UWP is not going to support .Net 5 or above.
    It’s not the preferred platform any more, and anybody still using it should move on as quickly as possible.

    • Sukesh Ashok Kumar

      I believe he is new to Microsoft thus unaware.

    • Canol Gökel

      I was going to ask the same thing, are we still supposed to use UWP for new projects? I am confused right now…