Monday 23 February 2015

Chapter Twelve: Develop a Hello World app

Developing Windows  Metro Application is very easy,Lets develop a Hello world app happily & quickly :)

Windows 8 Metro application can be developed using:
C++ with XAML
(uses  Component Extensions, or C++CX, that allows the language to make better use of WinRT)
C# or Visual Basic with XAML (WinRT is directly accessible)
JavaScript with HTML5 and CSS3
(the Windows Runtime is supplemented by a Windows Library for JavaScript, or WinJS, which provides a number of system-level features for Metro style apps written in JavaScript.).
Create a "Hello, world" app (Windows Store apps using C#VB and XAML) (Windows).
Create a simple "Hello, world" Windows Store app using Extensible Application Markup Language (XAML) with Microsoft Visual Basic or C#.

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#.
Getting started
To create an app, you need Windows 8 and Microsoft Visual Studio Express 2012 for Windows 8. To download them.
You also need a developer license.
We assume you have a basic understanding of XAML.
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.
Step 1: Create a new project in Visual Studio
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".)
Select File>New Project.
The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display.
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.

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.
In the Name text box, enter "HelloWorld".
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 (largelogo.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.
In this example, you replace the default MainPage with a page that uses the Basic Page template..
To replace MainPage in the blank app
In Solution Explorer, right-click MainPage.xaml and select Delete.
Click OK to confirm the deletion.
Select Project>Add New Item. The Add New Item dialog box opens. It looks similar to the New Project dialog.
Under Visual C# or Visual Basic in the left pane, pick the Windows Store template type.
In the center pane, pick Basic Page as the type of page to add to your project.
Enter "MainPage.xaml" as the name for the page.
Important  If you leave the default name, "BasicPage1", the project will not build correctly.
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.
Click Build>Build solution to build the app.
Step 2: Start the app
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).
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.
 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.
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.xamlResourceDictionary located in the Common folder. StandardStyles.xaml provides a set of default styles that gives your app the Windows 8 look and feel.
XAML

<Applicationx:Class="HelloWorld.App"
xmlns="http:schemas.microsoft.comwinfx2006xamlpresentation"

xmlns:x="http:schemas.microsoft.comwinfx2006xaml"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 template -->

<ResourceDictionarySource="CommonStandardStyles.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. it contains a constructor that calls the InitializeComponentmethod. 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.
C#,VB

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

 The Blank Application template is documented at http:go.microsoft.comfwlink?LinkId=234227

namespaceHelloWorld
{
<summary>
Provides application-specific behavior to supplement the default Application class.
<summary>
sealedpartialclass 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>

protectedoverridevoidOnLaunched(LaunchActivatedEventArgsargs)
{
Frame rootFrame = Window.Current.Contentas 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))
{
thrownew 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>
privatevoidOnSuspending(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.
XAML

<common:LayoutAwarePage
x:Name="pageRoot"
x:Class="HelloWorld.MainPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
IsTabStop="false"
xmlns="http:schemas.microsoft.comwinfx2006xamlpresentation"
xmlns:x="http:schemas.microsoft.comwinfx2006xaml"
xmlns:local="using:HelloWorld"
xmlns:common="using:HelloWorld.Common"
xmlns:d="http:schemas.microsoft.comexpressionblend2008"
xmlns:mc="http:schemas.openxmlformats.orgmarkup-compatibility2006"
mc:Ignorable="d">

<Page.Resources>

<!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
<x:Stringx: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
    -->
<GridStyle="{StaticResourceLayoutRootStyle}">
<Grid.RowDefinitions>
<RowDefinitionHeight="140">
<RowDefinitionHeight="*">
<Grid.RowDefinitions>

<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinitionWidth="Auto">
<ColumnDefinitionWidth="*">
<Grid.ColumnDefinitions>
<Buttonx:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResourceBackButtonStyle}">
<TextBlockx:Name="pageTitle" Grid.Column="1" Text="{StaticResourceAppName}" Style="{StaticResourcePageHeaderTextStyle}">
<Grid>

<VisualStateManager.VisualStateGroups>

<!-- Visual states reflect the application's view state -->
<VisualStateGroupx:Name="ApplicationViewStates">
<VisualStatex:Name="FullScreenLandscape">
<VisualStatex:Name="Filled">

<!-- The entire page respects the narrower 100-pixel margin convention for portrait -->
<VisualStatex:Name="FullScreenPortrait">
<Storyboard>
<ObjectAnimationUsingKeyFramesStoryboard.TargetName="backButton" Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrameKeyTime="0" Value="{StaticResourcePortraitBackButtonStyle}">
<ObjectAnimationUsingKeyFrames>
<Storyboard>
<VisualState>

<!-- The back button and title have different styles when snapped -->
<VisualStatex:Name="Snapped">
<Storyboard>
<ObjectAnimationUsingKeyFramesStoryboard.TargetName="backButton" Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrameKeyTime="0" Value="{StaticResourceSnappedBackButtonStyle}">
<ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFramesStoryboard.TargetName="pageTitle" Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrameKeyTime="0" Value="{StaticResourceSnappedPageHeaderTextStyle}">
<ObjectAnimationUsingKeyFrames>
<Storyboard>
<VisualState>
<VisualStateGroup>
<VisualStateManager.VisualStateGroups>
<Grid>
<common:LayoutAwarePage>




MainPage.xaml.csvb
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.
C#, VB

using System;
usingSystem.Collections.Generic;
usingWindows.UI.Xaml.Controls;

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

namespaceHelloWorld
{
<summary>
A basic page that provides characteristics common to most applications.
<summary>
publicsealedpartialclassMainPage : HelloWorld.Common.LayoutAwarePage
    {
publicMainPage()
        {
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>
protectedoverridevoidLoadState(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>
protectedoverridevoidSaveState(Dictionary<String, Object>pageState)
        {
        }
    }
}

To modify the start page
Double-click MainPage.xaml in Solution Explorer to open it.
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.
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.
In the property menu, select Edit Resource. The Edit Resource dialog opens.
In the Edit Resource dialog, change the value from "My Application" to "Hello, world!".
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.
XAML
<x:Stringx:Key="AppName">Hello, world!<x:String>

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.
XAML
<StackPanelGrid.Row="1" Margin="120,30,0,0">
<TextBlockText="What's your name?">

<StackPanelOrientation="Horizontal" Margin="0,20,0,20">
<TextBoxx:Name="nameInput" Width="300" HorizontalAlignment="Left">
<ButtonContent="Say &quot;Hello&quot;">
<StackPanel>

<TextBlockx:Name="greetingOutput">
<StackPanel>


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

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
 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.
To add an event handler
In XAML or design view, select the "Say Hello" Button that you added to MainPage.xaml.
In the Properties Window, click the Events button ().
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".

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.
XAML
<ButtonContent="Say&quot;Hello&quot;" Click="Button_Click">

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.
C#, VB
privatevoidButton_Click(object sender, RoutedEventArgs e)
 {
greetingOutput.Text = "Hello, " + nameInput.Text + "!";
}

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.


Part 5: Style the start page
Choosing a theme
To switch to the light theme
In Solution Explorer, double click App.xaml to open it.
In the opening Application tag, add the RequestedTheme property with its value set to Light.
XAML
RequestedTheme="Light"

Here's the full Application tag with the light theme added.
XAML
<Applicationx:Class="HelloWorld.App"xmlns="http:schemas.microsoft.comwinfx2006xamlpresentation" xmlns:x=http:schemas.microsoft.comwinfx2006xaml
xmlns:local="using:HelloWorld"RequestedTheme="Light">
Press F5 to build and run the app. Now it uses the light theme.

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:
XAML

<ResourceDictionary.MergedDictionaries>

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

To style an element
Double-click MainPage.xaml in Solution Explorer to open it.
In XAML or design view, select the "What's your name?" TextBlock that you added previously.
In the Properties Window, click the Properties button ().
Expand the Miscellaneous group and find the Style property.
Click the property marker next to the Style property to open the menu.
In the menu, select Local Resource>BasicTextStyle.
BasicTextStyle is a resource defined in the StandardStyles.xamlResourceDictionary.

In the XAML design surface, the appearance of the text changes. In the XAML editor, the XAML for the TextBlock is updated.
XAML
<TextBlockText="What's your name?" Style="{StaticResourceBasicTextStyle}">
Repeat the process to assign the BasicTextStyle 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.
XAML
<StackPanelGrid.Row="1" Margin="120,30,0,0">
<TextBlockText="What's your name?" Style="{StaticResourceBasicTextStyle}">
<StackPanelOrientation="Horizontal" Margin="0,20,0,20">
<TextBoxx:Name="nameInput" Width="300" HorizontalAlignment="Left">
<ButtonContent="Say &quot;Hello&quot;" Click="Button_Click">

<StackPanel>
<TextBlockx:Name="greetingOutput" Style="{StaticResourceBasicTextStyle}">
<StackPanel>
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
Here, you create a new style and apply it to the greetingOutputTextBlock. You put the style in the ResourceDictionary in App.xaml.
To use your own style
In XAML or design view, select the greetingOutputTextBlock that you added to MainPage.xaml.
Expand the Miscellaneous group and find the Style property.
Click the property marker next to the Style property to open the menu.
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 BasicTextStyle is still applied from the previous step, so that's the style you'll modify a copy of.
In the Create Style Resource dialog, enter "BigGreenTextStyle" as the resource key, and select the option to define the resource in the application.

Click OK. The new style is created in App.xaml and the TextBlock is updated to use the new style resource.
XAML
<TextBlockx:Name="greetingOutput" Style="{StaticResourceBigGreenTextStyle}">

Click the property marker next to the Style property to open the menu again.
In the menu, select Edit Resource. App.xaml opens in the editor.
Note  Nothing is shown in the XAML designer for App.xaml.
In the "BigGreenTextStyle" resource, change the Foreground value to "Green" and the FontSize value to "36".
XAML
<Stylex:Key="BigGreenTextStyle" TargetType="TextBlock">
<SetterProperty="Foreground" Value="Green">
<SetterProperty="FontSize" Value="36">
<SetterProperty="FontFamily" Value="{StaticResourceContentControlThemeFontFamily}">
<SetterProperty="TextTrimming" Value="WordEllipsis">
<SetterProperty="TextWrapping" Value="Wrap">
<SetterProperty="Typography.StylisticSet20" Value="True">
<SetterProperty="Typography.DiscretionaryLigatures" Value="True">
<SetterProperty="Typography.CaseSensitiveForms" Value="True">
<Style>

Press F5 to build and run the app. The greeting is now displayed in large, green letter

By:
Khushbu Wadhwani,
Senior Windows app developer,
References:MSDN,Microsoft developer forum





No comments:

Post a Comment