Sdílet prostřednictvím


Part 1: Create a "Hello, world" app (Windows Store apps using C#/VB and XAML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

This tutorial teaches you how to create a simple "Hello, world" Windows Store app using Extensible Application Markup Language (XAML) with Microsoft Visual Basic or C#. It's the first tutorial in a series that teach you what you need to know to build Windows Store apps.

Important  This tutorial is intended for use with Microsoft Visual Studio 2013 and Windows 8.1. Parts of it will not work correctly with Microsoft Visual Studio 2012 and Windows 8.

 

In this tutorial, you learn how to:

  • Create a new project
  • Add XAML content to your start page
  • Handle touch, pen, and mouse input
  • Switch between the light and dark themes
  • Create your own custom styles

We show you how to create a Windows Store app using XAML with Visual Basic or C#.

Before you start...

  • To complete this tutorial, you need Windows 8.1 and Visual Studio 2013. To download them, see Get the tools.
  • You also need a developer license. For instructions, see Get a developer license.
  • We assume you have a basic understanding of XAML and the concepts in the XAML overview.
  • We assume you're using the default window layout in Microsoft Visual Studio. If you change the default layout, you can reset it in the Window menu by picking the Reset Window Layout command.
  • You can see the complete code for this tutorial in Part 1 complete code.

Step 1: Create a new project in Visual Studio

  1. Launch Visual Studio 2013.

    The Visual Studio 2013 start screen appears.

    (Going forward, we'll refer to Visual Studio 2013 as just "Visual Studio".)

  2. Select File > New Project.

    The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display.

  3. In the left pane, expand Installed > Templates, then expand Visual Basic or Visual C# and pick the Windows Store template type. The dialog's center pane displays a list of project templates for Windows Store apps.

  4. In the center pane, select the Blank App template.

    The Blank App template creates a minimal Windows Store app that compiles and runs, but contains no user interface controls or data. You add controls and data to the app over the course of these tutorials.

  5. In the Name text box, enter "HelloWorld".

  6. Click OK to create the project.

    Visual Studio creates your project and displays it in the Solution Explorer.

Although the Blank App is a minimal template, it still contains a lot of files:

  • A manifest file (package.appxmanifest) that describes your app (its name, description, tile, start page, and so on) and lists the files that your app contains.
  • A set of large and small logo images (Logo.scale-100.png and SmallLogo.scale-100.png)to display in the start screen.
  • An image (StoreLogo.scale-100.png) to represent your app in the Windows Store.
  • A splash screen (SplashScreen.scale-100.png) to show when your app starts.
  • XAML and code files for the app (App.xaml and App.xaml.cs/.vb) .
  • A start page (MainPage.xaml) and an accompanying code file (MainPage.xaml.cs/.vb) that run when your app starts.

These files are essential to all Windows Store apps using Visual Basic or C#. Any project that you create in Visual Studio contains them.

Replace the MainPage

The MainPage in the Blank App project template is based on the Blank Page template. It contains the minimum amount of XAML and code to instantiate a Page. However, when you create an app for the Windows Store, you must do more. For example, even a simple one page app must adapt to different layouts and views, save its state when suspended, and restore its state when resumed. The other project and Page templates in Visual Studio include some additional code and helper classes that help you with view and state management. When you use the Blank App project template, you typically replace the blank MainPage with one of the other Page templates to take advantage of the layout and helper classes they provide.

In this example, you replace the default MainPage with a page that uses the Basic Page template. Later tutorials in this series depend on the helper classes used by this template for view and state management. For more info about the Page templates you can choose in Visual Studio, see C#, VB, and C++ item templates.

To replace MainPage in the blank app

  1. In Solution Explorer, right-click MainPage.xaml and select Delete.

  2. Click OK to confirm the deletion.

  3. Select Project > Add New Item. The Add New Item dialog box opens. It looks similar to the New Project dialog.

  4. Under Visual C# or Visual Basic in the left pane, pick the Windows Store template type.

  5. In the center pane, pick Basic Page as the type of page to add to your project.

  6. Enter "MainPage.xaml" as the name for the page.

    Important  If you leave the default name, "BasicPage1", the project will not build correctly.

     

  7. Click Add.

    The first time you add a new page to the Blank App template (other than a Blank Page), Visual Studio shows a dialog with a message that the addition depends on files that are missing from your project. Click Yes to add these files. Files for several utility classes are added to your project in the Common folder.

    The XAML and code behind files for your page are added to the project.

  8. Click Build > Build solution to build the app.

    Important  The new page will show an error in the designer until you build the helper classes it depends on.

     

Step 2: Start the app

At this point, you created a very simple app. If you want to see what it looks like, press F5 to build, deploy, and launch your app in debugging mode. A default splash screen appears first. The splash screen is defined by an image (SplashScreen.scale-100.png) and a background color (specified in our app's manifest file). We don't cover it here, but it's easy to customize your splash screen. (To find out how, see Adding a splash screen.)

The splash screen disappears, and then your app appears. It contains a black screen and the title "My Application".

There's no button or command to close the app. You can use the close gesture or Alt+F4 to close it, but you typically don't close Windows Store apps, as we discuss more in Part 2: Manage app lifecycle and state. Press the Windows key to go to the Start screen, then show all apps; notice that deploying the app adds its tile to the Apps screen. To run the app again, tap or click its tile on the Apps screen, or press F5 in Visual Studio to run it in debugging mode.

It doesn't do much—yet—but congratulations, you've built your first Windows Store app!

To stop debugging the app, press Alt+Tab to return to Visual Studio. In Visual Studio, click Debug > Stop debugging to close the app. You can't edit in Visual Studio while you're debugging.

For more info, see Running Windows Store apps from Visual Studio.

Step 3: Modify your start page

What's in the files?

When you create a new project that uses the Blank App template, Visual Studio creates an app that contains a handful of files. To view and edit the files, double-click the file in the Solution Explorer. You can expand a XAML file just like a folder to see its associated code file. By default, XAML files open in a split view that shows both the design surface and the XAML editor.

In this tutorial, you work with just a few of the files listed previously: App.xaml, App.xaml.cs/.vb, MainPage.xaml, and MainPage.xaml.cs/.vb.

App.xaml

App.xaml is where you declare resources that are used across the app.

<Application
    x:Class="HelloWorld.App"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld">

</Application>

App.xaml.cs/vb

App.xaml.cs/.vb is the code-behind file for App.xaml. Code-behind is the code that is joined with the XAML page's partial class. Together, the XAML and code-behind make a complete class. App.xaml.cs/.vb is the entry point for your app. Like all code-behind pages, it contains a constructor that calls the InitializeComponent method. You don't write the InitializeComponent method. It's generated by Visual Studio, and its main purpose is to initialize the elements declared in the XAML file. App.xaml.cs/.vb also contains methods to handle activation and suspension of the app. You add some code to these methods in Part 2: Manage app lifecycle and state.

using System;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Blank Application template is documented at https://go.microsoft.com/fwlink/p/?LinkID=234227

namespace HelloWorld
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {

#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}
' The Blank Application template is documented at https://go.microsoft.com/fwlink/p/?LinkID=234227

''' <summary>
''' Provides application-specific behavior to supplement the default Application class.
''' </summary>
NotInheritable Class App
    Inherits Application

    ''' <summary>
    ''' Invoked when the application is launched normally by the end user.  Other entry points
    ''' will be used when the application is launched to open a specific file, to display
    ''' search results, and so forth.
    ''' </summary>
    ''' <param name="e">Details about the launch request and process.</param>
    Protected Overrides Sub OnLaunched(e As Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
#If DEBUG Then
        ' Show graphics profiling information while debugging.
        If System.Diagnostics.Debugger.IsAttached Then
            ' Display the current frame rate counters
            Me.DebugSettings.EnableFrameRateCounter = True
        End If
#End If

        Dim rootFrame As Frame = TryCast(Window.Current.Content, Frame)

        ' Do not repeat app initialization when the Window already has content,
        ' just ensure that the window is active

        If rootFrame Is Nothing Then
            ' Create a Frame to act as the navigation context and navigate to the first page
            rootFrame = New Frame()
            If e.PreviousExecutionState = ApplicationExecutionState.Terminated Then
                ' TODO: Load state from previously suspended application
            End If
            ' Place the frame in the current Window
            Window.Current.Content = rootFrame
        End If
        If rootFrame.Content Is Nothing Then
            ' When the navigation stack isn't restored navigate to the first page,
            ' configuring the new page by passing required information as a navigation
            ' parameter
            If Not rootFrame.Navigate(GetType(MainPage), e.Arguments) Then
                Throw New Exception("Failed to create initial page")
            End If
        End If

        ' Ensure the current window is active
        Window.Current.Activate()
    End Sub

    ''' <summary>
    ''' Invoked when application execution is being suspended.  Application state is saved
    ''' without knowing whether the application will be terminated or resumed with the contents
    ''' of memory still intact.
    ''' </summary>
    ''' <param name="sender">The source of the suspend request.</param>
    ''' <param name="e">Details about the suspend request.</param>
    Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs) Handles Me.Suspending
        Dim deferral As SuspendingDeferral = e.SuspendingOperation.GetDeferral()
        ' TODO: Save application state and stop any background activity
        deferral.Complete()
    End Sub

End Class

MainPage.xaml

In the MainPage.xaml file you define the UI for your app. You can add elements directly using XAML markup, or you can use the design tools provided by Visual Studio. The Basic Page template creates a new class called MainPage (or whatever name you enter) that inherits from Page. It also includes some simple content, like a back button and page title, and provides methods for navigation and state management.

<Page
    x:Name="pageRoot"
    x:Class="HelloWorld.MainPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld"
    xmlns:common="using:HelloWorld.Common"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">My Application</x:String>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
    </Grid>
</Page>

MainPage.xaml.cs/vb

MainPage.xaml.cs/.vb is the code-behind page for MainPage.xaml. Here you add your app logic and event handlers. The Basic Page template includes 2 methods where you can save and load the page state.

using HelloWorld.Common;
using System;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Basic Page item template is documented at https://go.microsoft.com/fwlink/p/?LinkID=234237

namespace HelloWorld
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }


        public MainPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion
    }
}
' The Basic Page item template is documented at https://go.microsoft.com/fwlink/p/?LinkID=234237

''' <summary>
''' A basic page that provides characteristics common to most applications.
''' </summary>
Public NotInheritable Class MainPage
    Inherits Page

    ''' <summary>
    ''' NavigationHelper is used on each page to aid in navigation and 
    ''' process lifetime management
    ''' </summary>
    Public ReadOnly Property NavigationHelper As Common.NavigationHelper
        Get
            Return Me._navigationHelper
        End Get
    End Property
    Private _navigationHelper As Common.NavigationHelper

    ''' <summary>
    ''' This can be changed to a strongly typed view model.
    ''' </summary>
    Public ReadOnly Property DefaultViewModel As Common.ObservableDictionary
        Get
            Return Me._defaultViewModel
        End Get
    End Property
    Private _defaultViewModel As New Common.ObservableDictionary()

    Public Sub New()

        InitializeComponent()
        Me._navigationHelper = New Common.NavigationHelper(Me)
        AddHandler Me._navigationHelper.LoadState, AddressOf NavigationHelper_LoadState
        AddHandler Me._navigationHelper.SaveState, AddressOf NavigationHelper_SaveState
    End Sub

    ''' <summary>
    ''' Populates the page with content passed during navigation.  Any saved state is also
    ''' provided when recreating a page from a prior session.
    ''' </summary>
    ''' <param name="sender">
    ''' The source of the event; typically <see cref="NavigationHelper"/>
    ''' </param>
    ''' <param name="e">Event data that provides both the navigation parameter passed to
    ''' <see cref="Frame.Navigate"/> when this page was initially requested and
    ''' a dictionary of state preserved by this page during an earlier
    ''' session.  The state will be null the first time a page is visited.</param>
    Private Sub NavigationHelper_LoadState(sender As Object, e As Common.LoadStateEventArgs)

    End Sub

    ''' <summary>
    ''' Preserves state associated with this page in case the application is suspended or the
    ''' page is discarded from the navigation cache.  Values must conform to the serialization
    ''' requirements of <see cref="Common.SuspensionManager.SessionState"/>.
    ''' </summary>
    ''' <param name="sender">
    ''' The source of the event; typically <see cref="NavigationHelper"/>
    ''' </param>
    ''' <param name="e">Event data that provides a dictionary of state preserved by this page 
    ''' during an earlier session.  The state will be null the first time a page is visited.</param>
    Private Sub NavigationHelper_SaveState(sender As Object, e As Common.SaveStateEventArgs)

    End Sub

#Region "NavigationHelper registration"

    ''' The methods provided in this section are simply used to allow
    ''' NavigationHelper to respond to the page's navigation methods.
    ''' 
    ''' Page specific logic should be placed in event handlers for the  
    ''' <see cref="Common.NavigationHelper.LoadState"/>
    ''' and <see cref="Common.NavigationHelper.SaveState"/>.
    ''' The navigation parameter is available in the LoadState method 
    ''' in addition to page state preserved during an earlier session.

    Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
        _navigationHelper.OnNavigatedTo(e)
    End Sub

    Protected Overrides Sub OnNavigatedFrom(e As NavigationEventArgs)
        _navigationHelper.OnNavigatedFrom(e)
    End Sub

#End Region


End Class

Modify the start page

Now, let's add some content to the app.

To modify the start page

  1. Double-click MainPage.xaml in Solution Explorer to open it.

  2. To change the page title, select the "My Application" text near the top of the page in the XAML designer.

    Make sure the TextBlock named pageTitle is showing in the Properties panel. By default, the Properties panel is below the Solution Explorer panel.

  3. The Properties panel contains a list of properties and values for the selected object. Next to each property value is a property marker, a small box symbol that you can click to open a property menu. The Text property marker is green to indicate that it's set to a resource.

    Under Common in the Properties panel, click the property marker for the Text property. The property menu opens.

  4. In the property menu, select Edit Resource. The Edit Resource dialog opens.

  5. In the Edit Resource dialog, change the value from "My Application" to "Hello, world!".

  6. Click OK.

    Instead of entering the app name directly into the text block, you updated a string resource that the text block's Text property is bound to. Using a resource like this makes text reusable, easier to maintain, and easier to localize. In MainPage.xaml, the XAML for the AppName resource definition is updated like this.

    <x:String x:Key="AppName">Hello, world!</x:String>
    
  7. In the XAML editor, add the controls for the UI.

    In the root Grid, immediately after the Grid that contains the back button and page title, add this XAML. It contains a StackPanel with a TextBlock that asks the user's name, a TextBox element to accept the user's name, a Button, and another TextBlock element.

            <StackPanel Grid.Row="1" Margin="120,30,0,0">
                <TextBlock Text="What's your name?"/>
                <StackPanel Orientation="Horizontal" Margin="0,20,0,20">
                    <TextBox x:Name="nameInput" Width="300" HorizontalAlignment="Left"/>
                    <Button Content="Say &quot;Hello&quot;"/>
                </StackPanel>
                <TextBlock x:Name="greetingOutput"/>
            </StackPanel>
    

    We talk more about XAML layout in Part 3: Navigation, layout, and views.

  8. Press F5 to run the app. It looks like this.

    You can type in the TextBox, but right now, clicking the Button doesn't do anything. In the next steps, you create an event handler for the button's Click event that displays a personalized greeting. You add the event handler code to your MainPage.xaml.cs/.vb file.

Step 4: Create an event handler

XAML elements can send messages when certain events occur. These event messages give you the opportunity to take some action in response to the event. You put your code to respond to the event in an event handler method. One of the most common events in many apps is a user clicking a Button.

Let's create an event handler for your button's Click event. The event handler will get the user's name from the nameInputTextBox control and use it to output a greeting to the greetingOutputTextBlock.

Using events that work for touch, mouse, and pen input

What event should you handle? Because they can run on a variety of devices, design your Windows Store apps with touch input in mind. Your app must also be able to handle input from a mouse or a stylus. Fortunately, events such as Click and DoubleTapped are device-independent. If you're familiar with Microsoft .NET programming, you might have seen separate events for mouse, touch, and stylus input, like MouseMove, TouchMove, and StylusMove. In Windows Store apps, these separate events are replaced with a single PointerMoved event that works equally well for touch, mouse, and stylus input.

To add an event handler

  1. In XAML or design view, select the "Say Hello" Button that you added to MainPage.xaml.

  2. In the Properties Window, click the Events button ().

  3. Find the Click event at the top of the event list. In the text box for the event, type the name of the function that handles the Click event. For this example, type "Button_Click".

  4. Press Enter. The event handler method is created and opened in the code editor so you can add code that's executed when the event occurs.

    In the XAML editor, the XAML for the Button is updated to declare the Click event handler like this.

    <Button Content="Say &quot;Hello&quot;" Click="Button_Click"/>
    
  5. Add code to the event handler that you created in the code behind page. In the event handler, retrieve the user's name from the nameInputTextBox control and use it to create a greeting. Use the greetingOutputTextBlock to display the result.

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                greetingOutput.Text = "Hello, " + nameInput.Text + "!";
            }
    
        Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
            greetingOutput.Text = "Hello, " & nameInput.Text & "!"
        End Sub
    
  6. Press F5 to build and run the app. When you enter your name in the text box and click the button, the app displays a personalized greeting.

Step 5: Style the start page

Choosing a theme

It's easy to customize the look and feel of your app. By default, your app uses resources with a dark style. The system resources also include a light theme. Let's try it out and see what it looks like.

To switch to the light theme

  1. In Solution Explorer, double click App.xaml to open it.

  2. In the opening Application tag, add the RequestedTheme property with its value set to Light.

    RequestedTheme="Light"
    

    Here's the full Application tag with the light theme added.

    <Application
        x:Class="HelloWorld.App"
        xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:HelloWorld" 
        RequestedTheme="Light">
    
  3. Press F5 to build and run the app. Now it uses the light theme.

Which theme should you use? Whichever one you want. For apps that mostly display images or video, we recommend using the dark theme, and for apps that contain a lot of text, we recommend using the light theme. If you're using a custom color scheme, use the theme that goes best with your app's look and feel.

Note  The theme is applied when the app is started. You can't change themes while the app is running.

 

Using system styles

Right now, all the text is very small and difficult to read. You can easily apply the system styles to elements in your app to make them look great.

To style an element

  1. Double-click MainPage.xaml in Solution Explorer to open it.

  2. In XAML or design view, select the "What's your name?" TextBlock that you added previously.

  3. In the Properties Window, click the Properties button ().

  4. Expand the Miscellaneous group and find the Style property.

  5. Click the property marker next to the Style property to open the menu.

  6. In the menu, select System Resource > BaseTextBlockStyle.

    In the XAML design surface, the appearance of the text changes. In the XAML editor, the XAML for the TextBlock is updated.

    <TextBlock Text="What's your name?" Style="{ThemeResource BaseTextBlockStyle}"/>
    
  7. Repeat the process to assign the BaseTextBlockStyle to the greetingOutputTextBlock element.

    Tip  There's no text in this TextBlock, but when you hover the mouse pointer over the XAML design surface, a blue outline shows where the TextBlock is so you can select it.

     

    Your XAML now looks like this.

    <StackPanel Grid.Row="1" Margin="120,30,0,0">
        <TextBlock Text="What's your name?" Style="{ThemeResource BaseTextBlockStyle}"/>
        <StackPanel Orientation="Horizontal" Margin="0,20,0,20">
            <TextBox x:Name="nameInput" Width="300" HorizontalAlignment="Left"/>
            <Button Content="Say &quot;Hello&quot;" Click="Button_Click"/>
        </StackPanel>
        <TextBlock x:Name="greetingOutput" Style="{ThemeResource BaseTextBlockStyle}"/>
    </StackPanel>
    
  8. Press F5 to build and run the app. It now looks like this.

Creating your own styles

To customize the look and feel of your app, you can create your own styles. For more info, see Quickstart: Styling controls.

Here, you create a new style and apply it to the greetingOutputTextBlock. You put the style in the resources section of MainPage.xaml.

To use your own style

  1. In XAML or design view, select the greetingOutputTextBlock that you added to MainPage.xaml.

  2. Expand the Miscellaneous group and find the Style property.

  3. Click the property marker next to the Style property to open the menu.

  4. In the menu, select Convert to New Resource.... The Create Style Resource dialog opens.

    Note  The style that you want to modify must already be applied to the control. In this example, the BaseTextBlockStyle is still applied from the previous step, so that's the style you'll modify a copy of.

     

  5. In the Create Style Resource dialog, enter "BigGreenTextStyle" as the resource key, and select the option to define the resource in this document.

  6. Click OK. The new style is created in the resources section of MainPage.xaml and the TextBlock is updated to use the new style resource.

    <TextBlock x:Name="greetingOutput" Style="{StaticResource BigGreenTextStyle}"/>
    

    The TextBlock is using the new style, but it still looks the same. You need to edit the style you created to give it a new look.

  7. Click the property marker next to the Style property to open the menu again.

  8. In the menu, select Edit Resource.

  9. In the "BigGreenTextStyle" resource, add a Setter for the Foreground property with the value of "Green".

        <Setter Property="Foreground" Value="Green"/>
    

    Note  As you change the style in the XAML editor, you can see the effect of your changes in the design view.

     

  10. In the FontSizeSetter, change the value to "36".

  11. Delete the Setter for the LineHeight property.

    <!-- Delete this Setter. -->
    <Setter Property="LineHeight" Value="20"/>
    

    Here's the final XAML for the style.

    <Style x:Key="BigGreenTextStyle" TargetType="TextBlock">
        <Setter Property="Foreground" Value="Green"/> 
        <Setter Property="FontSize" Value="36"/>
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="TextTrimming" Value="CharacterEllipsis"/>
        <Setter Property="TextWrapping" Value="Wrap"/>
        <Setter Property="Typography.StylisticSet20" Value="True"/>
        <Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
        <Setter Property="Typography.CaseSensitiveForms" Value="True"/>
        <Setter Property="LineStackingStrategy" Value="BlockLineHeight"/>
        <Setter Property="TextLineBounds" Value="TrimToBaseline"/>
        <Setter Property="OpticalMarginAlignment" Value="TrimSideBearings"/>
    </Style>
    
  12. Press F5 to build and run the app. The greeting is now displayed in large, green letters.

Summary

Congratulations, you're done with the first tutorial! You learned how to add content to a Windows Store app. You also learned how to add interactivity and how to style the app.

See the code

Did you get stuck, or do you want to check your work? If so, see Part 1 complete code.

Next steps

In the next part of this tutorial series, you learn how to app lifecycle works and how to save your app's state. Go to Part 2: Manage app lifecycle and state.