Tuesday, April 2, 2013

Windows 8 XAML - Hello World Application


The following article is from MSDN and explains how to create the application in windows 8 using XAML and programming language is C#.  You can also check this in the URL 




Prerequesties:
  • To complete this tutorial, you need Windows 8 and Microsoft Visual Studio Express 2012 for Windows 8. 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 Express 2012 for Windows 8.
    The Visual Studio Express 2012 for Windows 8 start screen appears.
    (Going forward, we'll refer to Visual Studio Express 2012 for Windows 8 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.
    Visual Studio new project window
  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.
    Visual Studio 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.png and smalllogo.png)to display in the start screen.
  • An image (storelogo.png) to represent your app in the Windows Store.
  • A splash screen (splashscreen.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 Appproject 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 thePage templates you can choose in Visual Studio, see C#, VB, and C++ item templates.
Hh986965.wedge(en-us,WIN.10).gifTo 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 Projectdialog.
  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.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".
Initial app screen
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; notice that deploying the app adds its tile to the last group on the Start screen. To run the app again, tap or click its tile on the start 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 debuggingto close the app. You can't edit in Visual Studio while you're debugging.

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. This file contains a ResourceDictionary that has a reference to the StandardStyles.xaml ResourceDictionary located in the Common folder. StandardStyles.xaml provides a set of default styles that gives your app the Windows 8 look and feel.
<Application
    x:Class="HelloWorld.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld">

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>

                <!-- 
                    Styles that define common aspects of the platform look and feel
                    Required by Visual Studio project and item templates
                 -->
                <ResourceDictionary Source="Common/StandardStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>

        </ResourceDictionary>
    </Application.Resources>
</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 theInitializeComponent 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 http://go.microsoft.com/fwlink/?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 when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            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 (args.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), args.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();
        }
    }
}


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 LayoutAwarePage. The LayoutAwarePage class extends the base Page class and provides methods for navigation, state management, and view management. The Basic Page template also includes some simple content, like a back button and page title.
<common:LayoutAwarePage
    x:Name="pageRoot"
    x:Class="HelloWorld.MainPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    IsTabStop="false"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld"
    xmlns:common="using:HelloWorld.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>

        <!-- 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 Style="{StaticResource LayoutRootStyle}">
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/>
            <TextBlock x:Name="pageTitle" Grid.Column="1" Text="{StaticResource AppName}" Style="{StaticResource PageHeaderTextStyle}"/>
        </Grid>

        <VisualStateManager.VisualStateGroups>

            <!-- Visual states reflect the application's view state -->
            <VisualStateGroup x:Name="ApplicationViewStates">
                <VisualState x:Name="FullScreenLandscape"/>
                <VisualState x:Name="Filled"/>

                <!-- The entire page respects the narrower 100-pixel margin convention for portrait -->
                <VisualState x:Name="FullScreenPortrait">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PortraitBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>

                <!-- The back button and title have different styles when snapped -->
                <VisualState x:Name="Snapped">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="pageTitle" Storyboard.TargetProperty="Style">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedPageHeaderTextStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>
</common:LayoutAwarePage>

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. TheBasic Page template includes 2 methods where you can save and load the page state.
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace HelloWorld
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : HelloWorld.Common.LayoutAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <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>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <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>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }
    }
}


Modify the start page

Now, let's add some content to the app.
Hh986965.wedge(en-us,WIN.10).gifTo 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'sText 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 before the <VisualStateManager.VisualStateGroups> tag, 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.
    App screen with controls
    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 thenameInput TextBox control and use it to output a greeting to the greetingOutput TextBlock.

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 asClick 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 MouseMoveTouchMove, 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.
Hh986965.wedge(en-us,WIN.10).gifTo 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 (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".
    Events list in the properties window
  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 nameInput TextBox control and use it to create a greeting. Use the greetingOutput TextBlock to display the result.
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                greetingOutput.Text = "Hello, " + nameInput.Text + "!";
            }
    
    
  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.
    App screen with message display

Part 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.
Hh986965.wedge(en-us,WIN.10).gifTo 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="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://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.
    App screen with 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 standard styles

Earlier in this tutorial, we pointed out that the App.xaml file contains a reference to the StandardStyles.xamlResourceDictionary:
<ResourceDictionary.MergedDictionaries>

    <!-- 
        Styles that define common aspects of the platform look and feel
        Required by Visual Studio project and item templates
    -->
    <ResourceDictionary Source="Common/StandardStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>


Right now, all the text is very small and difficult to read. You can easily apply the standard styles to elements in your app to make them look great.
Hh986965.wedge(en-us,WIN.10).gifTo 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 (Events 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 Local Resource > BasicTextStyle.
    BasicTextStyle is a resource defined in the StandardStyles.xaml ResourceDictionary.
    Visual Studio properties window
    In the XAML design surface, the appearance of the text changes. In the XAML editor, the XAML for the TextBlockis updated.
    <TextBlock Text="What's your name?" Style="{StaticResource BasicTextStyle}"/>
    
    
  7. Repeat the process to assign the BasicTextStyle to the greetingOutput TextBlock 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="{StaticResource BasicTextStyle}"/>
        <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="{StaticResource BasicTextStyle}"/>
    </StackPanel>
    
    
  8. Press F5 to build and run the app. It now looks like this.
App screen with styled text

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 greetingOutput TextBlock. You put the style in theResourceDictionary in App.xaml.
Hh986965.wedge(en-us,WIN.10).gifTo use your own style
  1. In XAML or design view, select the greetingOutput TextBlock 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, theBasicTextStyle 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 the application.
    Create style resource dialog
  6. Click OK. The new style is created in App.xaml and the TextBlock is updated to use the new style resource.
    <TextBlock x:Name="greetingOutput" Style="{StaticResource BigGreenTextStyle}"/>
    
    
  7. Click the property marker next to the Style property to open the menu again.
  8. In the menu, select Edit Resource. App.xaml opens in the editor.
    Note  Nothing is shown in the XAML designer for App.xaml.
  9. In the "BigGreenTextStyle" resource, change the Foreground value to "Green" and the FontSize value to "36".
    <Style x:Key="BigGreenTextStyle" TargetType="TextBlock">
        <Setter Property="Foreground" Value="Green"/>
        <Setter Property="FontSize" Value="36"/>
        <Setter Property="FontFamily" Value="{StaticResource ContentControlThemeFontFamily}"/>
        <Setter Property="TextTrimming" Value="WordEllipsis"/>
        <Setter Property="TextWrapping" Value="Wrap"/>
        <Setter Property="Typography.StylisticSet20" Value="True"/>
        <Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
        <Setter Property="Typography.CaseSensitiveForms" Value="True"/>
    </Style>
    
    
  10. Press F5 to build and run the app. The greeting is now displayed in large, green letters.
    App screen with green text

No comments:

Post a Comment