Create your first Windows Store app with Blend, part 2: the details page (XAML & C#)

You can develop a Windows Store app more quickly and efficiently by using the collection of XAML design tools in Blend for Visual Studio. As you walk through this tutorial, you'll build a simple app, PickaFlick, in which you can browse new movies in a list that's generated through an API from Rotten Tomatoes.

Blend PickaFlick app

By downloading this project from the samples gallery, you can review not only the code but also all of its assets so that you can follow along and build the project as you go.

Note Note

To run this app, you must register with Rotten Tomatoes to get a key and paste it into the code.

In part 1 of this tutorial, you created the PickaFlick home page. In part 2, you'll:

In addition to project templates, both Blend and Visual Studio provide item templates, which contain commonly used code. You can easily add one to a project to help speed up your app development. See Templates to speed up your app development.

For the PickaFlick app, you'll add an item template for a blank page to the existing project. The page will be the movie display page of your app.

To add a blank page item template

  1. Right-click the project file in the Projects panel, and click New Item.

    The New Item dialog box opens.

    Blend - New Item template - XAML
  2. In the list of item templates, click Blank Page.

  3. In the Name text box, type MovieDisplay.xaml, and then click OK to add the item template.

Now you'll change the background of MovieDisplay.xaml

To change the background of MovieDisplay.xaml

  1. In the Objects and Timeline panel, click Grid.

  2. In the Properties panel, in the Brush category, click the Solid color brush icon .

  3. In the Hex value text box, type #D5BF9A, and then press Enter.

    Blend Properties panel - Background property

    The Grid tag in the code view now includes the attribute Background="#FFD5BF9A" (the Alpha value defaults to 100%, or FF), and the new background color is displayed on the design surface.

The PickaFlick app requires a JSON serializer in order to convert JSON into .NET objects that can be consumed by Windows Store apps built using C#. You can write your own JSON serializer, or download one using the NuGet Package Manager in Microsoft Visual Studio. You can easily switch to Visual Studio from within Blend to accomplish this.

In this procedure, you'll switch to Visual Studio to download Json.NET, a JSON serializer, then save your changes and switch back to Blend to continue your work.

To install Json.NET using the NuGet Package Manager

  1. In the Projects panel, right-click PickaFlick, and then click Edit in Visual Studio.

    Visual Studio opens the PickaFlick project. When you are prompted to reload the files, click Reload All.

    Tip Tip

    Because you already opened Visual Studio in part 1 of this tutorial, the Visual Studio may be hidden behind Blend after you click Edit in Visual Studio.

  2. In Solution Explorer, right-click the project file, and then click Manage NuGet Packages.

    Visual Studio - Manage NuGet Packages - XAML
  3. In the Manage NuGet Packages dialog box, type Json.Net in the Search text box. Press Enter.

  4. In the Results List, click the Install button to the right of Json.NET.

    Visual Studio Manage NuGet Packages dialog box
  5. After the package has finished installing, click Close.

    The Json.NET home page appears in the document window, and a reference to Newtonsoft.Json appears in the References folder in Solution Explorer.

The code for the PickaFlick app pulls the data from the Rotten Tomatoes web site and builds .NET objects from the data retrieved that you can then consume directly in your app.

To add the code to your project

  1. Right-click Solution Explorer, click Add, and then click New Folder.

    Visual Studio - Add New Folder
  2. In Solution Explorer, click the new folder, and then type DataModel.

    Visual Studio - Data Model Folder
  3. Right-click the DataModel folder, point to Add, and then click New Item, or press Ctrl+Shift+A.

  4. In the Add New Item dialog box, click Class, and then type MovieData.cs. Click Add.

  5. In MovieData.cs, replace class MovieData {} with the following:

    // This class represents a movie. It contains properties the describe the movie.
        public class MovieData
        {
            public MovieData(string title, string summary, string image)
            {
                this.Title = title;
                this.Summary = summary;
                this.Image = image;
    
            }
            public string Title { get; set; }
            public string Summary { get; set; }
            public string Image { get; set; }
        }
    
  6. Press Ctrl+Shift+A. Make sure Class is selected. In the Add New Item dialog box, click Class, and then type PickaFlickQuery.cs. Click Add.

  7. In PickaFlickQuery.cs, add the following after using System.Threading.Tasks;:

    using System.IO;
    using System.Runtime.InteropServices.WindowsRuntime;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using System.Collections.ObjectModel;
    using System.Net;
    using System.Net.Http;
    using Newtonsoft.Json;
    using System.IO.Compression;
    
  8. Replace class PickaFlickQuery {} with the following code:

        public class PickaFlickQuery
        {
            protected Uri Uri { get; private set; }
            // A collection class used to store a list of MovieData objects.
            public ObservableCollection<MovieData> results = new ObservableCollection<MovieData>();
            private bool hasExecutedQuery;
    
            public PickaFlickQuery(Uri uri)
            {
                this.Uri = uri;
            }
    
            // Executes a query to obtain information about movies.
            // This property also stores the movies in a collection class.
            public ObservableCollection<MovieData> Results
            {
                get
                {
                    if (!hasExecutedQuery)
                    {
                        this.ExecuteQuery();
                    }
    
                    return this.results;
                }
            }
    
            // Calls a service to obtain a list of movies. This method stores each movie
            // in a collection object.
            private async void ExecuteQuery()
            {
                try
                {          
                    HttpClient httpClient = new HttpClient();
    
                    var response = await httpClient.GetAsync(this.Uri);
    
                    string responseText = "";
    
                    IEnumerable<string> headerValues = Enumerable.Empty<string>();
    
                    if (response.Content.Headers.TryGetValues("Content-Encoding", out headerValues))
                    {
                        foreach (string headerValue in response.Content.Headers.GetValues("Content-Encoding"))
                        {
                            if (headerValue == "gzip")
                            {
                                using (var responseStream = await response.Content.ReadAsStreamAsync())
                                using (var decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress))
                                using (var streamReader = new StreamReader(decompressedStream))
                                {
                                    responseText = streamReader.ReadToEnd();
                                }
                            }
                        }   
                    }
                    if (responseText == "")
                    {
                        var stream = await response.Content.ReadAsStreamAsync();
                        var streamReader = new StreamReader(stream);
                        responseText = streamReader.ReadToEnd();
                    }
    
                
                    // Convert the stream to JSON so that it is easier to iterate through
                    // each item in the stream.
                    dynamic myObj = JsonConvert.DeserializeObject(responseText);
                    dynamic movies = myObj.movies;
    
                    // Iterate through the collection of JSON objects to obtain information
                    // each movie in the collection.
                    foreach (dynamic movie in movies)
                    {
                        string title = movie.title;
                        string summary = movie.synopsis;
                        string image = movie.posters.detailed;
    
                        // Create a Moviedata object by using movie information and add 
                        // that object to a collection.
                        results.Add(new MovieData(title, summary, image));
                     }
                 
                    hasExecutedQuery = true;
                }
                catch (Exception)
                {
                    hasExecutedQuery = false;
                    showErrorMessage();
                }
            }
            private async void showErrorMessage()
            {
                var msg = new Windows.UI.Popups.MessageDialog
                    ("The service is unavailable or there was a problem with the service.");
    
                msg.Commands.Add(new Windows.UI.Popups.UICommand("Try again?"));
    
                msg.Commands.Add(new Windows.UI.Popups.UICommand("I'll try again later."));
    
                msg.DefaultCommandIndex = 0;
                msg.CancelCommandIndex = 1;
    
                var results = await msg.ShowAsync();
    
                if (results.Label == "I'll try again later.")
                {
                    hasExecutedQuery = true;
                    this.Results.Clear();
                }
                else
                {
                    hasExecutedQuery = false;
                    this.Results.Clear();
                }
    
    
            }
    
        }
    
  9. Press Ctrl+Shift+A. Make sure Class is selected. In the Add New Item dialog box, click Class, and then type PickaFlickViewModel.cs. Click Add.

  10. In PickaFlickViewModel.cs, replace class PickaFlickViewModel {} with the following:

    // Provides an object that returns movie data. You can bind to this class in the designer.
        // For example, by referencing this class in the ItemSource property of a GridView control. 
        public class PickaFlickViewModel
        {
    // A Rotten Tomatoes API key is required. See http://go.microsoft.com/fwlink/?LinkId=313841 
            private static readonly string apikey = "Insert API Key Here";
            private static readonly string baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
            private static readonly string moviesSearchUrl = baseUrl + "/lists/movies/box_office.json?apikey=" + apikey;
    
            private static readonly Uri uri = new Uri(moviesSearchUrl);
    
            private readonly PickaFlickQuery query = new PickaFlickQuery(uri);
            
            // Property that returns a collection of MovieData objects. 
            public PickaFlickQuery Query
            {
                get
                {
                    return this.query;
                }
            }
        }
    
    Important noteImportant

    If you have a Rotten Tomatoes API key, replace the "Insert API Key Here" text with the key. The app will not run as expected without the key.

  11. Press Ctrl+Shift+S to save all of your changes, and then switch back to Blend.

  12. In Blend, when you're asked if you want to reload the project. Click Yes.

    Blend Reload Files message

By setting the DataContext, you are specifying the source data for the objects that are displayed in your app.

To set the DataContext

  1. Press Ctrl+B to build the project so that the changes that you made in Visual Studio are available in Blend.

  2. Make sure that MovieDisplay.xaml is open by clicking the MovieDisplay.xaml tab at the top of the document window. In the Objects and Timeline panel, click Grid.

  3. In the Properties panel, to the right of DataContext, click New.

    Blend - Properties Panel - DataContext
  4. In the Select Object dialog box, click PickaFlickViewModel. Click OK.

    Tip Tip

    Clear the Show all assemblies checkbox (in the lower left corner of the dialog box) if the list is too long to view easily.

    Blend - DataContext - Select Object dialog box

You can easily create a data-bound GridView that displays the data for your movie app by dragging the Results node from the DataContext section of the Data panel onto the design surface. The GridView and an associated DataTemplate is automatically created, and the data is displayed on the design surface.

The PickaFlick app doesn't use a GridView control. It uses a FlipView control which enables you to easily flip through items in a list. You can quickly create this view by adding a FlipView to your project, and then dragging the Results node directly onto the FlipView in the Objects and Timeline panel.

Note Note

If you create a grid view of the data and then delete it, the original DataTemplate remains in the XAML. If you create an additional grid view of the data, another DataTemplate is created with a number appended to the x:Key value. For example, if the first DataTemplate x:Key attribute is MovieTemplate, the second DataTemplate x:Key is MovieTemplate1.

To create a view of the data using a FlipView control

  1. In the Assets panel, click Controls, and then double-click FlipView.

    Blend - Assets - FlipView
  2. In the Data Context section of the Data panel, click and then drag Results : (MovieData) and then drop it onto the FlipView control in the Objects and Timeline panel.

    Tip Tip

    If the Results node isn't visible, expand the nodes in the Data Context section until you locate it.

    Blend - Objects and Timeline - FlipView

    The data now appears on the design surface inside the FlipView control. You are now ready to customize the layout of the data.

    Blend - Design Surface - FlipView
    Tip Tip

    If an unauthorized access exception is triggered and displayed on the design surface, double-check the API key and make sure that it is entered correctly in the code.

The Flipview is in place, and the data is loaded, but the movie display doesn't look quite right. You can style the generated data template so that it looks the way you want it to look, and then refine the data bindings so that the data displayed is the data that you want.

When you dragged the Results panel onto the FlipView, a data template was automatically generated. You can modify the template, customizing it so that it looks more like the data displayed in the finished sample app.

To edit the generated template

  1. Right-click FlipView in the Objects and Timeline panel, point to Edit Additional Templates, then point to Edit Generated Items (ItemTemplate), and then click Edit Current.

    Blend - Edit Generated Template
  2. Press Ctrl and, in the Objects and Timeline panel, click Border and StackPanel. Right-click, and then click Delete.

  3. In the Objects and Timeline panel, click Grid. In the Properties panel, in the Layout category, to the right of Width, click Set to Auto Blend Set to Auto icon. Repeat for Height.

  4. To the right of Margin, click Advanced Properties 12e06962-5d8a-480d-a837-e06b84c545bb, and then click Reset.

You are now ready to being designing your custom template.

The Grid layout panel is default panel for Blend projects. By following the design guidelines for Windows Store apps in conjunction with the Grid layout panel, you can style an app that adheres to the Windows 8 style guidelines. For more information about the guidelines, see Laying out an app page.

According to the guidelines, the basic unit of measurement for a Windows Store app is 20 × 20 pixels, and each unit is further divided into sub-units of 5 × 5 pixels. The layout is based on a grid that's defined by a header, a left margin, and a content area. According to the guidelines, the major elements of the grid are:

  • Page header   The baseline of the page header should be 5 units, or 100 pixels, from the top.

  • Left margin   The left margin should be 6 units, or 120 pixels, from the left edge.

  • Content region   The top margin should be 7 units, or 140 pixels, from the top.

You can modify objects by using adorners, which are handles that appear. Object adorners appear at the corners and in the middle of the object outlines. Adorners also appear at the ends of guidelines and gridlines. When you create a grid, you can use an insert adorner to place the gridline where you want it.

You have three options for sizing rows and columns in a grid, and these options affect the arrangement of the objects in the grid. The sizing options are:

  • Pixel   Uses pixel values to set fixed sizes.

  • Star (*)   Uses star values, and is similar to percentage widths.

  • Auto   Uses relative width, meaning that the objects in the grid will resize when the parent object resizes.

The layout grid uses both pixel-width and star-width columns.

To create the layout grid columns

  1. The original template consisted of two columns (identified by a grid column adorner) and one row. Click the grid column adorner and drag it to the right.

    Blend grid column adorner
  2. In the value editor that appears, click the drop-down arrow to open the list, and then click Pixel.

    Blend - grid value edito - Pixel
  3. In the numeric value editor, type 120.

    Blend - pixel value editor
  4. Point to the top of the grid to the left of the first adorner that you created, and then click the orange insert adorner. Repeat two more times.

    You now have five columns.

  5. In the value editor for the second column, type 1. Leave the Sizing option set to Star (*).

  6. In the value editor for the third column, type 40. Set the Sizing option set to Pixel.

  7. In the value editor for the fourth column, type 1. Leave the Sizing option set to Star (*).

  8. In the value editor for the fifth column, type 120. Set the Sizing option set to Pixel.

To create the layout rows

  1. On the design surface, point to the dotted blue line to the left of the grid, and then click the orange insert adorner that appears.

    Blend - orange insert adorner
  2. In the value editor that appears, click the drop-down arrow to open the list, and then click Pixel. In the numeric value editor, type 100.

  3. Point to a location under the gridline that you just created, and then click the orange insert adorner that appears.

  4. Open the value editor list, and then click Pixel. In the numeric value editor, type 40.

    This setting places the second gridline 40 pixels below the first gridline, at the 140-pixel mark.

You should now have five columns and three rows.

Blend layout grid for PickaFlick

You are now ready to begin adding content to the grid. The first object you'll add is the logo.

To add and style the logo

  1. Make sure Grid is selected in the Objects and Timeline panel. In the Projects panel, in the Assets folder, double-click SmallLogo-Chicken.png to add it to the design surface.

  2. In the Properties panel, in the Layout category, set HorizontalAlignment to Center Blend - HorizontalAlignment - Center and VerticalAlignment to Bottom Blend VerticalAlignment Bottom.

  3. To the right of Margin, click Advanced Properties 12e06962-5d8a-480d-a837-e06b84c545bb, and then click Reset.

  4. In the Common category, set Stretch to None.

    Small chicken logo for PickaFlick app in Blend

To complete the template, you'll continue to add objects to the template, and then you'll bind data to those objects. You can then modify the display of the objects so that the data looks the way that you want it to.The type of objects that you use will be determined by the kind of data that you want to bind to. For example, the movie poster image will be bound to an Image control, while the movie title and summary will be bound to TextBlock controls.

To add and position the movie title

  1. With Grid selected in the Objects and Timeline panel, in the Assets panel, double-click TextBlock to add it to the design surface.

    A new Textblock object is added to the upper left corner of the design surface. Press Esc to exit text-editing mode.

  2. To position the Textblock in the column and row in the grid where you want it to be, in the Layout category of the Properties panel, set the following:

    • Row   0

      This positions the Textblock in the top row.

    • RowSpan   1

      The title should not extend beyond a single row.

    • Column   1

      Because column and row numbering begins at 0, this setting positions the Textblock in the second column.

    • ColumnSpan   3

      Spanning multiple columns will ensure that longer titles will display in a single row.

    The TextBlock now appears at the top right of the second column.

  3. To position the TextBlock inside the row where you want it to be, set VerticalAlignement to Bottom Blend VerticalAlignment Bottom.

You are now ready to style the text in the TextBlock. In the next procedure, you'll set the font and size of the text, and then change the color of the text.

To style the text in the TextBlock

  1. According to the Guidelines for fonts (Windows Store apps), the header for a Windows 8 app should use 42pt Segoe UI Light.

    In the Text category of the Properties panel, select Segoe UI Light from the Font list.

  2. For the size, you can either select from the list to the right of the Font list, or type directly into the value editor. For the header, type 42pt, and then press Enter.

    Blend Text category - Font & Size
  3. Notice that the bottom of the characters floats above the baseline of the text block.

    Blend header text above baseline

    This extra space is for descenders (the tail of the lower-case letter g, for example). You want the base of the main text to rest on the baseline, with space for any descenders that might be part of a title below the baseline. To adjust the baseline, in the Layout category, set the bottom margin to -18.

    The text is now resting on the baseline.

    Blend header text on baseline
  4. In the Brush category of the Properties panel, click the color eyedropper Blend color eyedropper icon.

    Blend color editor

    Point to the chicken image in the upper left of the design surface. Notice that the color of the text in the TextBlock changes depending on the part of the chicken image that you are pointing to. When you find a shade of red that you like, click on the image to set the font color.

    Blend TextBlock color

You are now ready to bind the movie title data to the TextBlock.

To bind the movie title data to the TextBlock object

  1. In the Common category, to the right of Text, click Advanced Properties 12e06962-5d8a-480d-a837-e06b84c545bb, and then click Create Data Binding.

  2. In the Create Data Binding for [TextBlock].Text dialog box, click Title and then click OK.

    Blend create data binding - title

Next, you'll add and style the movie art.

To add and position the movie art

  1. With Grid selected in the Objects and Timeline panel, in the Projects panel, in the Assets folder, double-click Temp.png to add it to the design surface.

    A new Image object with Temp.png as the Source is added to the design surface.

  2. In the Layout category of the Properties panel, set the following:

    • Row   3

    • RowSpan   1

    • Column   1

    • ColumnSpan   1

  3. Set HorizontalAlignment to Center Blend - HorizontalAlignment - Center and VerticalAlignment to Top .

  4. To the right of Margin, click Advanced Properties 12e06962-5d8a-480d-a837-e06b84c545bb, and then click Reset.

Don't worry about the aspect ratio of the temporary image. You'll fix the display after you bind the movie image to the Image object.

To bind the movie art to the Image object

  1. In the Common category, to the right of Source, click Advanced Properties 12e06962-5d8a-480d-a837-e06b84c545bb, and then click Create Data Binding.

  2. In the Create Data Binding for [Image].Source dialog box, click Image and then click OK.

    Blend Create Data Binding dialog box - movie image
  3. In the Common category, in the Stretch list, click Uniform.

Next, you'll add and style the summary. Some movie summaries may be quite long, extending beyond the height of the screen. To enable scrolling of the summary, you'll add a ScrollViewer object to the template, and then add a TextBlock to the ScrollViewer to display the text.

To add and position the movie summary

  1. With Grid selected in the Objects and Timeline panel, in the Assets panel, double-click ScrollViewer to add it to the design surface.

    A new ScrollViewer object is added to the upper left corner of the design surface.

  2. With ScrollViewer selected in the Objects and Timeline panel, in the Layout category, to the right of Width, click Set to Auto Blend Set to Auto icon. Repeat for Height.

  3. To position the Textblock, in the Layout category of the Properties panel, set the following:

    • Row   2

    • RowSpan   1

    • Column   3

    • ColumnSpan   1

    The ScrollViewer now appears at the top left of third row in the fourth column.

  4. With ScrollViewer selected in the Objects and Timeline panel, in the Assets panel, double-click TextBlock to add a second TextBlock to the design surface.

    A new Textblock object is added to the ScrollViewer object. Press Esc to exit text-editing mode.

It will be easier to style the text after you bind the TextBlock element to the movie summary data.

To bind the movie summary data to the TextBlock object

  1. In the Common category, to the right of Text, click Advanced Properties 12e06962-5d8a-480d-a837-e06b84c545bb, and then click Create Data Binding.

  2. In the Create Data Binding for [TextBlock].Text dialog box, click Summary and then click OK.

    Blend Create Data Binding dialog - movie summary

You are now ready to style the summary text.

To style the text in the TextBlock

  1. The Guidelines for fonts (Windows Store apps) recommends Segoe UI Semilight for the body font for a Windows 8 app.

    In the Text category of the Properties panel, select Segoe UI Semilight from the Font list.

  2. For the size, you can either select from the list to the right of the Font list, or click inside the value editor, and then use the Up and Down arrows to choose a font size. Press Enter. Select a font size that you like by reviewing the display on the design surface.

  3. In the Brush category of the Properties panel, click the color eyedropper Blend color eyedropper icon to select a color from the display, or click inside the color editor to select a color from the palette.

    Blend color editor palette

Because Blend displays a live view of your app, you can see whether or not it looks the way that you want it to without running it. You can also preview what your app might look like in different displays by using the Device panel.

To enable Display in the Device panel

  • To enable the Display option, exit template-editing mode by clicking Return to scope Return to scope button.

Tip Tip

Not all options are enabled for all project or item templates. For example, the High contrast and Theme settings apply to the selected project and item templates such as the Grid App, Hub App, and Split App project templates and the Split Page, Items Page and Hub Page item templates.

Some options must be enabled in the manifest designer. For example, if you set Minimum width to 320px, a message appears alerting you that this option must be enabled in the app manifest. For more information, see Configure an app package by using the manifest designer.

Blend Device panel

If you run your app, the main page will display, and the chicken button image will change when you hover the pointer over it. If you click the button, nothing will happen, because a click event trigger hasn't been defined for the control. You can use a built-in behavior to add a NavigateToPageAction behavior to the button that will take you to the movie display page.

Add a NavigateToPageAction behavior to the Button control

  1. Switch to MainPage.xaml. With Button selected in the Objects and Timeline panel, in the Assets panel, in the Behaviors category, double-click NavigateToPageAction to add it to the Button.

    An EventTriggerBehavior and a NavigateToPageAction appear in the Objects and Timeline panel.

    Blend Objects & Timeline - NavigateToPageAction
  2. In the Properties panel, the Common category appears. In the TargetPage drop-down list, click MovieDisplay.xaml.

    Blend NavigateToPageAction properties
    Tip Tip

    As an alternative, you can click EventTriggerBehavior in the Objects and Timeline panel, and then, in the Properties panel, click the Actions (Collection) button. In the DependencyObjectCollection Editor: Actions dialog box, in the Properties section, click MovieDisplay in the TargetPage drop-down list.

Press F5 to build and run your app. Click the chicken button to open the movie details page. Click through the new releases by using the arrows at the right and left of the screen.

Press Alt+F4 to close the app.

If this were a real app, the next step would be to get your app published. For more information on how to get your app into the Windows Store, see Overview of publishing an app to the Windows Store.

Show:
© 2014 Microsoft