Tuesday, July 1, 2014

Win8Dev Tutorial: Know about LayoutAwarePage of Wndows Store app



In last chapter “Navigate between Pages” we discussed the basics of page navigation, where we navigated from one page to another page using the Frame.Navigate(type, obj). We also discussed how to pass an object as query string parameter.

Today in this chapter we will discuss more advanced page navigation using the LayoutAwarePage which comes with the Grid and Split application template by default.

Continuing the last chapter on building Windows Store application, today we will explore more about the standard navigation. If you create a Grid app or a Split app, you will find some common files created inside the project under the “Common” folder. Among them “LayoutAwarePage” implements many navigational APIs to do the standard navigational operations.

Windows Store Project

“LayoutAwarePage” inherits from “Page” and hence you will be able to use all the basic operations that Page class offers you. In addition to those, you will find more new APIs in that. If you are using a blank XAML page, you just have to use “LayoutAwarePage” insists of “Page” as shown below in order to use the advanced layout and navigation features,

LayoutAwarePage of a Windows Store Project

It is always better to use this class as the root of the page if you are using navigations from one page to another. The important methods that you will be able to use from this page are: “GoHome()”, “GoBack()” and “GoForward()” which implicitly calls the Frame methods to complete these operations. The implementation of those methods are shared here for clear visibility:
 
// Invoked as an event handler to navigate backward in the page's associated
// Frame until it reaches the top of the navigation stack.
protected virtual void GoHome(object sender, RoutedEventArgs e)
{
    // Use the navigation frame to return to the topmost page
    if (this.Frame != null)
    {
        while (this.Frame.CanGoBack) this.Frame.GoBack();
    }
}
 
// Invoked as an event handler to navigate backward in the navigation stack
// associated with this page's Frame.
protected virtual void GoBack(object sender, RoutedEventArgs e)
{
    // Use the navigation frame to return to the previous page
    if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
}
 
// Invoked as an event handler to navigate forward in the navigation stack
// associated with this page's Frame
protected virtual void GoForward(object sender, RoutedEventArgs e)
{
    // Use the navigation frame to move to the next page
    if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward();
}


To see how these methods work, you can chose any one of the Grid and Split applications from the Windows Store project template. Let’s take Grid app for an example here. The main screen of the Grid app uses a GridView to show thumbnails of the groups as below:

Grid app of Windows Store Project

Clicking the group header will navigate you to the group details page. You can see a back button here just before the page title. It is by default available in all the pages but based on navigation status it becomes visible or collapse. Here’s the code to show the 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>

Grid app of Windows Store Project

Similarly clicking the items from the group page or group details page will navigate you to the group item details page. You can easily navigate to the next or previous item by just sliding the screen or navigational keys of the keyboard.

Grid app of Windows Store Project

This navigational operations are handle by the two events named AcceleratorKeyActivated and PointerPressed of the core window. The first invokes when a user uses keystrokes to navigate and the second one invokes when a user uses mouse clicks, touch screen taps or other similar interactions to navigate between pages. Here comes the declaration of the said events:
 
// Invoked on every keystroke, including system keys such as Alt key combinations,
// when this page is active and occupies the entire window. Used to detect keyboard
// navigation between pages even when the page itself doesn't have focus.
private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender,
                                                    AcceleratorKeyEventArgs args);
 
// Invoked on every mouse click, touch screen tap, or equivalent interaction when
// this page is active and occupies the entire window. Used to detect browser-style 
// next and previous mouse button clicks to navigate between pages.
private void CoreWindow_PointerPressed(CoreWindow sender, PointerEventArgs args);

In the below screenshot you can see the navigational arrows that pops up when you move your mouse inside the screen. An user can easily navigate between the pages by tapping those buttons or pressing the navigational keys in the keyboard.

Grid app of Windows Store Project

Not only this, the LayoutAwarePage also automatically handles the screen orientation changes properly. You can use visual states of each pages to visualize the screen orientation and view.

This post will help you to understand the LayoutAwarePage implementation and uses of it. Try out by creating a sample project yourself, you will come to know more about it. If you have any queries, drop a line below and I will try to answer you as soon as I can. Happy coding.

Win8Dev Tutorial: Navigate between Pages in Windows Store apps



Let’s begin with our fourth chapter of building Windows Store application development using Visual Studio 2012. In the previous chapters of this tutorial series, we got familiar with this project template and built a basic “Hello World” application.

Today in this chapter we will learn how to navigate from one page to another page in Windows 8 Store applications. So, continue reading.

Introduction to Page Navigation

It’s not at all difficult to implement the navigation in Windows Store applications but if you are a Silverlight and/or Windows Phone application developer and just moved to this field, you might find difficulty developing a navigation application. In Windows Phone, we use NavigationService.Navigate() to navigate to a different page from a page. Also, we pass a relative or absolute URL to the Navigate() method. Here it’s bit different. Let’s discuss on it more.

In Windows 8 Store applications, every page has a “Frame” object, which implements the following properties and methods to support easy navigations:

GoBack()Navigates to the most recent item in back navigation history, if a Frame manages its own navigation history.
GoForward()Navigates to the most recent item in forward navigation history, if a Frame manages its own navigation history.
Navigate(type, args)Navigates to the page specified.
BackStackDepthThe number of entries in the navigation back stack.
CanGoBackGets a value that indicates whether there is at least one entry in back navigation history.
CanGoForwardGets a value that indicates whether there is at least one entry in forward navigation history.

Check out the parameters of Navigate(type, args) method. You can see that, you can’t pass navigation Uri like we did in Silverlight and Windows Phone. Instead of passing the relative/absolute Uri path here, we have to pass the type of the page.

Let’s suppose we want to navigate from MainPage.xaml to SecondaryPage.xaml. You have to call navigate method by passing the type of second page. For example:
 
Frame.Navigate(typeof(SecondaryPage)); // simple navigation
Frame.Navigate(typeof(SecondaryPage), obj); // navigation with query parameter

Let’s see a practical example. For this, we will need to create a basic blank Windows Store application. For more details, check out the previous chapter: “Begin with your First 'Hello World' app”, which will give you the basic idea.

Begin with XAML Screen

Once you created the project, you will find a page called “MainPage.xaml”. Open it and modify the XAML code with a Button and a TextBlock as shared below (assuming you are familiar with XAML):
 
<Page
    x:Class="NavigationDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Main Page" Style="{StaticResource HeaderTextStyle}"
                   Margin="100,50"/>
        <Button Style="{StaticResource BackButtonStyle}" Margin="403,0,0,668"
                RenderTransformOrigin="0.5, 0.5" Tapped="OnNextButtonTapped">
            <Button.RenderTransform>
                <RotateTransform Angle="180"/>
            </Button.RenderTransform>
        </Button>
    </Grid>
</Page>

This will change the MainPage UI as shown below. We will implement the next button tap event to handle the navigation to a different page later.

Main Page

Now create another page named as “SecondaryPage.xaml” in the root folder and modify this page with the following code. This will have a back button and a TextBlock.
 
<Page
    x:Class="NavigationDemo.SecondaryPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Secondary Page" Style="{StaticResource HeaderTextStyle}" 
                   Margin="100,50"/>
        <Button Style="{StaticResource BackButtonStyle}" Margin="29,0,0,674" 
                Tapped="OnBackButtonTapped"/>
    </Grid>
</Page>

The new page will look as below. Here the back button implementation will have logic to navigate to the previous page in the navigation stack.

Secondary Page

This ends the basic design of our sample application. You can do more with that but it is not require to complex this demo as you are reading it to know more about this implementation.

Implementing the Navigation between Pages

To implement the navigation between those pages, you need to modify the code behind of both the screens. In both the cs file, you will find the Tap event. In the MainPage.xaml.cs implementation, call the Navigate() method and pass the other page type as shown below, which when called will navigate you to the secondary page:
 
// Forward button tap implementation (in MainPage.xaml.cs)
private void OnNextButtonTapped(object sender, TappedRoutedEventArgs e)
{
    Frame.Navigate(typeof (SecondaryPage));
}
 
 
// Back button tap implementation  (in SecondaryPage.xaml.cs)
private void OnBackButtonTapped(object sender, TappedRoutedEventArgs e)
{
    if (Frame.CanGoBack)
    {
        Frame.GoBack();
    }
}

In the SecondaryPage.xaml.cs implementation (as shown above), first check whether the navigation can go to the previous page and if it can go, call the GoBack() method from the Frame itself.

As mentioned above, if you want to pass a query string parameter to the second page where you are navigating to, you can do so by passing the value or object as second parameter to the Navigate() method.

End Note

I hope that, this post will help you to understand the navigation mechanism in Windows Store application. After reading this chapter, you will be able to navigate the user from one page to another and also you will be able to send message to the other page.

Win8Dev Tutorial: Begin with your First “Hello World” Windows Store app

How to create your first Windows Store application?

Let’s open the Visual Studio 2012 IDE and go to File – New – Project to create a new Windows Store project. From the Visual C# category, we will select the Windows Store template category. In the right panel, chose Blank App (XAML) and give a good name (in our case, it is “HelloWorld”). Now click “OK” to continue. Momentarily the IDE will start creating your first project.

Create HelloWorld Windows Store app in Visual Studio 2012

Once the project has been created by the IDE, open the MainPage.xaml file and add a TextBlock from the toolbox inside the Grid as shown below:

Design the UI of the Application with a TextBlock

Select the TextBlock and move to the Properties panel. There you can set the text property of the control. Visual Studio 2012 gives a proper way to bind styles from the local resource. Click the small rectangle near to the Style property, navigate to Local Resource and from the secondary menu, select a style (e.g. HeaderTextStyle) as shown in the below screenshots:

Use the properties panel to style the control     Style the TextBlock with Local Resources

Styled TextBlock in the designer window

Here is the XAML code of what we have designed just now:
 
<Page x:Class="HelloWorld.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock HorizontalAlignment="Left" Height="101" Margin="81,99,0,0" 
                   TextWrapping="Wrap" Text="Hello World" VerticalAlignment="Top" 
                   Width="598" Style="{StaticResource HeaderTextStyle}"/>
    </Grid>
</Page>

Now in the design window, you will see similar to the above screen. You can drag other controls too and create your own UI for your first “HelloWorld” Windows Store application. Once your application design is ready, you can build and run that app to see what we developed just now.

Building and Running the Windows Store application

It’s time to build the project and run it to see our application running inside Windows 8. You can chose any one of the three options that Visual Studio 2012 provides to test our app. You can chose between the following locations:
      • Simulator – The app will be deployed in a simulator
      • Local Machine – The app will be deployed in your local development machine
      • Remote Machine – The app will be deployed in a remote Windows 8 PC
When you move your mouse to the debug option menu inside your Visual Studio 2012 IDE, you will see all the three options as shown below:

Choose the deployment environment

You can chose the one where you want to deploy and test your application. In our case, we will deploy it to Simulator to see how it looks inside a tablet. Here is the screenshot of the application hosted in the simulator:

Run the application inside Simulator

Now you are done with your first Windows Store application using Visual C# (XAML) and now you will be able to develop more applications using that simple project template.

End Note

In the next chapter, we will learn more about Windows Store application configuration and then we will proceed towards the other templates and coding tricks. Till then enjoy doing your hands dirty developing Windows Store applications.

Win8Dev Tutorial: Understand WinRT Project Templates and Structure

What are the Common Templates in each Category?

Each category has it’s own templates but among them three are common and they are “Blank App”, “Grid App” and “Split App”. You will find them in all the four categories and you will need any one of them while creating your Windows Store applications. Before going to other categories, let’s discuss these common basic templates first.

Blank Template

“Blank App” template creates a single page project for a Windows Store application which has no predefined controls of layouts. In the UI page, you will see it completely blank and you have to create everything from scratch.

Grid Template

“Grid App” template creates a three page project structure for a Windows Store application that navigates among grouped items arranged in a grid. The main page display all items in groups. When clicked, the page navigates to details pages of individual item.

Split Template

“Split App” template generates a two paged project for a Windows Store application that also navigates among a set of grouped items. The main page allows group selection while the other page displays an item list along with details for the selected item.

What are the Structures of individual core project?

When you create a Windows Store project with any one of the above mentioned templates, it will create the following project structures (shown as per each individual template):

Windows Store Various Project Structure

In the above project structures you will see a similarity between each one of them. Every project has two folders, App.xaml, a .pfx file and a .appxmanifest file in it. The basic folders are Assets (used to store resource images required by the application) and Common (to store the common code files used across the application). There is a third folder named DataModel (a repository of Models, View Models and Sample Data Source used by it) available only in Grid and Split project.

Each and every project will have a App.xaml file which is the basic entry point to the application, a Package.appxmanifest file to set the manifest information of the app and a [APPLICATION_NAME]_TemporaryKey.pfx file which stores the certificate key information. Rest of them are xaml pages based on the above selection.

What are the other Project Templates in each Category?

Apart from the common templates, each category has a set of various templates. Let’s see what are those in each category. This will make it easier for you to chose the category and project template before starting a new project.

In Visual C# and Visual Basic category, we have 3 additional project templates named “Class Library”, “Windows Runtime Component” and “Unit Test Library” as shown below:

Windows Store (Visual C#) Template

The class library project creates a managed class library for Windows Store apps and Windows Runtime Component. Windows Runtime Components can be used by Windows Store apps regardless of the programming languages in which the apps were written. The other template gives you easy access to write unit testing code directly.

Windows Store (Visual Basic) Template

If you are going to develop a direct 2D or direct 3D application, you should chose Visual C++ category as this category provides you the basic templates to start with that. In this category you will find the following additional templates:
        • Direct 2D App
        • Direct 3D App
        • DLL Library project
        • Static Library for Windows Store apps
        • Windows Runtime Component
        • Unit Test Library
Windows Store (Visual C  ) Template

The JavaScript category has “Fixed Layout” and “Navigation” templates to create a static and navigational Windows Store apps.

Windows Store (JavaScript) Template

Do remember that, if you chose JavaScript category, the application will be build using html, scripts and css where as in other categories the UI of the application will be build in XAML.

Summary

Today we discussed about the various project templates and project structures. Up to this, it was just the introduction to Windows Store apps for a beginners who came here to understand the requirements and to kick start their hands dirty with this.

From now onwards, we will work on C# category and focus on the development stuffs to learn Windows Store application development and continue on this series. Don’t forget to check out the coming chapters on this topic.