Windows 8.1 Resources

 

[patterns & practices] Prism for the Windows Runtime

The Prism library and the associated AdventureWorks Shopper RI demonstrate how to create Windows Store Apps using C# and XAML.checkoutpage.png

Overview

This project provides guidance to developers who want to create a Windows Store business app using C#, Extensible Application Markup Language (XAML), the Windows Runtime, and modern development practices. The guidance comes with source code for the Microsoft.Practices.Prism.StoreApps library, source code for the Microsoft.Practices.Prism.PubSubEvents library, the AdventureWorks product catalog and shopping cart reference implementation, and documentation. The guidance helps you implement MVVM with navigation and app life cycle management, validation, managed application data, implement controls, pages, touch, search, tiles, tile notifications, localization and accessibility. It also provides guidance on testing your app and tuning its performance.

Links

Blogs and Twitter

 Source:  http://prismwindowsruntime.codeplex.com/

Windows 8 App Design Reference Templates [Windows Store Apps]

Here is a list of templates for Windows Store Apps that can be found in Codeplex:

Windows 8 App Design Reference Template: Baby Journal
Windows 8 App Design Reference Template: Basic Game
Windows 8 App Design Reference Template: Block Style Color
Windows 8 App Design Reference Template: Block Style Picture
Windows 8 App Design Reference Template: Blocks
Windows 8 App Design Reference Template: Brick Style
Windows 8 App Design Reference Template: Cook Book
Windows 8 App Design Reference Template: Drawing
Windows 8 App Design Reference Template: E-Commerce Electronics
Windows 8 App Design Reference Template: E-Commerce Fashion
Windows 8 App Design Reference Template: ECommerce Jewellery
Windows 8 App Design Reference Template: Finance
Windows 8 App Design Reference Template: Financial Adviser
Windows 8 App Design Reference Template: Fitness
Windows 8 App Design Reference Template: Food
Windows 8 App Design Reference Template: Food and Dining
Windows 8 App Design Reference Template: Food Light
Windows 8 App Design Reference Template: Food Variable
Windows 8 App Design Reference Template: Forum
Windows 8 App Design Reference Template: Health & Fitness
Windows 8 App Design Reference Template: Health Management
Windows 8 App Design Reference Template: Invitation
Windows 8 App Design Reference Template: Language Convertor
Windows 8 App Design Reference Template: Lifestyle
Windows 8 App Design Reference Template: Lifestyle Light
Windows 8 App Design Reference Template: Matching
Windows 8 App Design Reference Template: Music
Windows 8 App Design Reference Template: News
Windows 8 App Design Reference Template: News and Weather
Windows 8 App Design Reference Template: News Big Image
Windows 8 App Design Reference Template: News Dark
Windows 8 App Design Reference Template: News Grey
Windows 8 App Design Reference Template: News Light Theme
Windows 8 App Design Reference Template: News Variable Tile
Windows 8 App Design Reference Template: Notes
Windows 8 App Design Reference Template: Photo Browser
Windows 8 App Design Reference Template: Pillar Block
Windows 8 App Design Reference Template: Planning Diary
Windows 8 App Design Reference Template: Product
Windows 8 App Design Reference Template: Recipe
Windows 8 App Design Reference Template: Restaurant
Windows 8 App Design Reference Template: Shoe Store
Windows 8 App Design Reference Template: Shopping
Windows 8 App Design Reference Template: Simple Grid
Windows 8 App Design Reference Template: Solution
Windows 8 App Design Reference Template: Standard Square
Windows 8 App Design Reference Template: Text Keyboard
Windows 8 App Design Reference Template: Tracking
Windows 8 App Design Reference Template: Translator
Windows 8 App Design Reference Template: Travel and Tourism
Windows 8 App Design Reference Template: Travel Dark Theme
Windows 8 App Design Reference Template: Travel Light Theme
Windows 8 App Design Reference Template: Travel Picture
Windows 8 App Design Reference Template: Tutor
Windows 8 App Design Reference Template: Tutor Advanced
Windows 8 App Design Reference Template: Unit Convertor
Windows 8 App Design Reference Template: Variable Grid Style A
Windows 8 App Design Reference Template: Variable Grid Style B
Windows 8 App Design Reference Template: Variable Grid Style C
Windows 8 App Design Reference Template: Variable Grid Style D

Sharing Code: Adding NavigationService

Introduction

This sample has the goal to show an example about NavigationService in share code scenarios, that will be registered in one Ioc container and injected by view model’s contructor. The idea is to have an INavigationService interface that is portable and used in portable view models, in pratice will have diferent implementation in the platform project.

The source can be get here.

Building the Sample

You only need Visual Studio 2012 and Windows 8, both the RTM version.

Description

Before starting the sample, I recommend to see the related samples that was created:

  1. Consuming Odata Service in Windows Store Apps (Include MVVM Pattern)
  2. Creating portable code in Windows Store Apps (PCL + MVVM + OData Services)
  3. Sharing Code between Windows Store and Windows Phone App (PCL + MVVM + OData)

In this moment we have a TitlesPage.xaml in both projects and in this samples we will create a second page called   TitleDetailsPage.xaml and implementation for navigate between them and passing parameters.

 

Let’s start!

The main points are:

  1. INavigationService
  2. NavigationService in Windows Store Apps
  3. NavigationService in Windows Phone Apps
  4. Others details

 

1. INavigationService

 

Navigation is a verify important point in one application, because it allow us to switch between page and in some cases send data between them. There are some points to analyze:

– In Windows Store app we navigate to type of the page that is an object and in Windows Phone apps we navigate to uri using the string name of the page;

– For pass parameter, we can send an object when is a Windows Store app,  but for Windows Phone app we need to create a query string with the parameter;

– more common features are the CanGoBack property and GoBack method;

 

In gerenal, the for navigation must have:

  • Navigation method (that allow parameters)
  • GoBack method
  • CanGoBack property

 

Another “little problem” is the fact in portable class libraries i cannot use the page type, and an solution for it is to navigate for the ViewModel that will be used in next page. With this my INvaigationService could be:

/// <summary> 
    /// The NavigationService interface. 
    /// </summary> 
    public interface INavigationService 
    { 
        /// <summary> 
        /// Gets a value indicating whether can go back. 
        /// </summary> 
        bool CanGoBack { get; } 

        /// <summary> 
        /// The go back. 
        /// </summary> 
        void GoBack(); 

        /// <summary> 
        /// The navigate. 
        /// </summary> 
        /// <param name="parameter"> 
        /// The parameter. 
        /// </param> 
        /// <typeparam name="TDestinationViewModel"> 
        /// The destination view model. 
        /// </typeparam> 
        void Navigate<TDestinationViewModel>(object parameter = null); 
    }
 Let’s see who it will be implemented in Windows Store apps.

 

2. NavigationService in Windows Store Apps

    /// <summary> 
    /// The navigation service. 
    /// </summary> 
    public class NavigationService : INavigationService 
    { 
        /// <summary> 
        /// The view model routing. 
        /// </summary> 
        private static readonly IDictionary<Type, Type> ViewModelRouting = new Dictionary<Type, Type>() 
                                                                      { 
                                                                          { 
                                                                              typeof(TitlesViewModel), typeof(TitlesPage) 
                                                                          }, 
                                                                          { 
                                                                              typeof(TitleDetailsViewModel), typeof(TitleDetailsPage) 
                                                                         } 
                                                                     }; 

        /// <summary> 
        /// Gets a value indicating whether can go back. 
        /// </summary> 
        public bool CanGoBack 
        { 
            get 
            { 
                return RootFrame.CanGoBack; 
            } 
        } 

        /// <summary> 
        /// Gets the root frame. 
        /// </summary> 
        private static Frame RootFrame 
        { 
            get { return Window.Current.Content as Frame; } 
        } 

        /// <summary> 
        /// The go back. 
        /// </summary> 
        public void GoBack() 
        { 
            RootFrame.GoBack(); 
        } 

        /// <summary> 
        /// Navigates the specified parameter. 
        /// </summary> 
        /// <typeparam name="TDestinationViewModel"> 
        /// The type of the destination view model. 
        /// </typeparam> 
        /// <param name="parameter"> 
        /// The parameter. 
        /// </param> 
        public void Navigate<TDestinationViewModel>(object parameter) 
        { 
            var dest = ViewModelRouting[typeof(TDestinationViewModel)]; 

            RootFrame.Navigate(dest, parameter); 
        } 
    }

3. NavigationService in Windows Phone Apps

The implementation for the windows phone could be something like the following code

 

 /// <summary> 
    /// The navigation service. 
    /// </summary> 
    public class NavigationService : INavigationService 
    { 
        /// <summary> 
        /// The view model routing. 
        /// </summary> 
        private static readonly Dictionary<Type, string> ViewModelRouting = new Dictionary<Type, string> 
                                                                    { 
                                                                          { 
                                                                              typeof(TitlesViewModel), "View/TitlesPage.xaml" 
                                                                          }, 
                                                                          { 
                                                                              typeof(TitleDetailsViewModel), "View/TitleDetailsPage.xaml" 
                                                                         } 
                                                                     }; 

        /// <summary> 
        /// Gets a value indicating whether can go back. 
        /// </summary> 
        public bool CanGoBack 
        { 
            get 
            { 
                return RootFrame.CanGoBack; 
            } 
        } 

        /// <summary> 
        /// Gets the root frame. 
        /// </summary> 
        private Frame RootFrame 
        { 
            get { return Application.Current.RootVisual as Frame; } 
        } 

        /// <summary> 
        /// Decodes the navigation parameter. 
        /// </summary> 
        /// <typeparam name="TJson">The type of the json.</typeparam> 
        /// <param name="context">The context.</param> 
        /// <returns>The json result.</returns> 
        public static TJson DecodeNavigationParameter<TJson>(NavigationContext context) 
        { 
            if (context.QueryString.ContainsKey("param")) 
            { 
                var param = context.QueryString["param"]; 
                return string.IsNullOrWhiteSpace(param) ? default(TJson) : JsonConvert.DeserializeObject<TJson>(param); 
            } 

            throw new KeyNotFoundException(); 
        } 

        /// <summary> 
        /// The go back. 
        /// </summary> 
        public void GoBack() 
        { 
            RootFrame.GoBack(); 
        } 

        /// <summary> 
        /// Navigates the specified parameter. 
        /// </summary> 
        /// <typeparam name="TDestinationViewModel">The type of the destination view model.</typeparam> 
        /// <param name="parameter">The parameter.</param> 
        public void Navigate<TDestinationViewModel>(object parameter) 
        { 
            var navParameter = string.Empty; 
            if (parameter != null) 
            { 
                navParameter = "?param=" + JsonConvert.SerializeObject(parameter); 
            } 

            if (ViewModelRouting.ContainsKey(typeof(TDestinationViewModel))) 
            { 
                var page = ViewModelRouting[typeof(TDestinationViewModel)]; 

                this.RootFrame.Navigate(new Uri("/" + page + navParameter, UriKind.Relative)); 
            } 
        } 
    }

 

There are some differences for each implementation, the big one is the way we sent parameters in Windows Phone app, because it must be a query string.

 

4. Others details
With this i need to register the view model and the NavigationService interface and implementation, in ViewModelLocator:

/// <summary> 
    /// This class contains static references to all the view models in the 
    /// application and provides an entry point for the bindings. 
    /// </summary> 
    public class ViewModelLocator 
    { 
        /// <summary> 
        /// Initializes a new instance of the ViewModelLocator class. 
        /// </summary> 
        public ViewModelLocator() 
        { 
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 

            if (!SimpleIoc.Default.IsRegistered<IServiceManager>()) 
            { 
               // For use the fake data do: 
               // FakeServiceManager.FakeImagePath = "ms-appx:///Images/FakeImage.png"; 
               // SimpleIoc.Default.Register<IServiceManager, FakeServiceManager>(); 
               SimpleIoc.Default.Register<IServiceManager, ServiceManager>(); 

               SimpleIoc.Default.Register<INavigationService, NavigationService>(); 
            } 

            SimpleIoc.Default.Register<TitlesViewModel>(); 
            SimpleIoc.Default.Register<TitleDetailsViewModel>(); 
        } 

        /// <summary> 
        /// Gets the titles view model. 
        /// </summary> 
        public TitlesViewModel TitlesViewModel 
        { 
            get 
            { 
                return ServiceLocator.Current.GetInstance<TitlesViewModel>(); 
            } 
        } 

        /// <summary> 
        /// Gets the title details view model. 
        /// </summary> 
        /// <value> 
        /// The title details view model. 
        /// </value> 
        public TitleDetailsViewModel TitleDetailsViewModel 
        { 
            get 
            { 
                return ServiceLocator.Current.GetInstance<TitleDetailsViewModel>(); 
            } 
        } 

        /// <summary> 
        /// The cleanup. 
        /// </summary> 
        public static void Cleanup() 
        { 
            // TODO Clear the ViewModels 
        } 
    }

and the TitlesViewModel  will be updated with an new method:

  /// <summary> 
        /// The show title details. 
        /// </summary> 
        /// <param name="myTitle"> 
        /// The my title. 
        /// </param> 
        /// <returns> 
        /// The <see cref="bool"/>. 
        /// </returns> 
        public bool ShowTitleDetails(MyTitle myTitle) 
        { 
            if (_navigationService != null) 
            { 
                _navigationService.Navigate<TitleDetailsViewModel>(myTitle); 
                return true; 
            } 

            return false; 
        }

and in TitlesPage.xaml.cs we will add the

 /// <summary> 
        /// Handles the OnItemClick event of the Title control. 
        /// </summary> 
        /// <param name="sender">The source of the event.</param> 
        /// <param name="e">The <see cref="ItemClickEventArgs" /> instance containing the event data.</param> 
        private void Title_OnItemClick(object sender, ItemClickEventArgs e) 
        { 
            var titlesViewModel = DataContext as TitlesViewModel; 
            if (titlesViewModel != null) 
            { 
                var item = e.ClickedItem as MyTitleItemView; 
                if (item != null) 
                { 
                    titlesViewModel.ShowTitleDetails(item.Item); 
                } 
            } 
        }

that allow to navigate to the next page. Here i am using the method from view model to keep the same code between platforms.

 

Note: The reason for this is besause there are differences between Behaviors between platforms, and the implementation i tested for Windows Store apps don´t liked.

 

Source Code Files

  • IServiceManager.cs has the IServiceManager interface and define the interface for the ServiceManager.
  • ServiceManager.cs has the ServiceManager class and it encapsulate the NetFlixService and exposes only the methods that is need in ViewModel.
  • FakeServiceManager.cs is the implementation of the IServiceManager, but is a fake data.
  • TitlesViewModel.cs has TitlesViewModel class and it is used for binding with the DataContext from TitlesPage.
  • TitleDetailsViewModel that represent the view model that will be binding to the TitleDetailsPage.
  • ViewModelLocator.cs has the ViewModelLocator class that help to binding the view model with the view.
  • ViewModelHelper.cs has the ViewModelHelper class the helps to create grouped data.
  • TitlesPage.xaml and TitlesPage.xaml.cs that is the main page.
  • TitleDetailsPage.xaml that represent the page with details from selected item in TitlesPage.xaml.
  • Templates.xaml is a resource dictionary that has the DataTemplate for the view.
  • NetFlixItemTemplateSelector.cs has the NetFlixItemTemplateSelector that is used for get the ItemTemplate for each item in gridView.
  • TitleDetailsPage.xaml that represent the page with details from selected item in TitlesPage.xaml.

More Information

Run the sample

This sample requires a Nuget package restore. For it, you should follow the steps:

Open the solution (.sln file), the aspect should be:

 

 

Go to Top Menu > Tools > Library Package Manager

 

 

We will see something like this:

 

Download process will start….

 

 

At the end, is recommend to close the solution and then open again.

 

To debug the app and then run it, press F5 or use Debug > Start Debugging. To run the app without   debugging, press Ctrl+F5 or use Debug > Start Without Debugging.

 

More Information

Ask me on twitter @saramgsilva

Portable Class Library – Articles and Sample References

For who is looking for articles/samples/presentations about portable class libraries, the following references is that i recommend to see!

(but can be more, add a comment with good references!)

Articles

Samples

PortableNotepad – This sample shows how to access non-portable functionality from portable code by creating a portable abstraction with platform-specific implementations.

Goals: Abstraction for Load / Save data in files

Projects: Windows Phone, Windows Store App, WPF App

ContosoHelpdesk– This demo show advanced concepts.

Goals: Navigation, inversion of control, and synchronizing data across multiple clients with Windows Azure Service Bus.

Projects: Windows Phone, Windows Store App

Note: Use Autofac portable library (IoC Container)

TwitterSearch – This sample shows how to create a twitter search client.

Goals: Twitter Search API, Azure Mobile Services,

Projects: Windows Phone, Windows Store App, Console App

Note: Use MVVMCross portable library

Disentanglement – This is a solver for Thinkfun’s Gordian’s Knot puzzle which runs on Windows and Windows Phone. It uses a Portable Class Library to share the solver code between the different platforms

Goals: Share the solver code.

Projects: Windows Phone App, Desktop App, Xbox App

PixPresenter – is a photo sharing app that enables you to connect to another device using Proximity (NFC) and a tap gesture, and then send pictures back and forth between the connected devices. It demonstrates code sharing techniques that you can use when developing an app for bot

Goals: Windows Runtime API common code

Projects: Windows Phone, Windows Store App (C# and C++)

Cross-Platform Mvvm Samples:

Presentations

[En] Building Android Apps with MVVM and Data Binding

[PT] Como deixar de fazer copy and paste entre windows store e windows phone apps
[En] Do not do more copy and paste between windows store and windows phone apps

[En] Developing for Windows Phone 8 and Windows 8

Sharing Code between Windows Store and Windows Phone App (PCL + MVVM + OData)

Introduction

This sample has the goal to show how to share code between Windows Store and Windows Phone App.

The initial code sample can be find here:

Creating portable code in Windows Store Apps (PCL + MVVM + OData Services)

Before you start, take a look in this presentation:

Do not do more copy and paste between windows store and windows phone apps

Get the code for this sample, here.

Building the Sample

You only need Visual Studio 2012 and Windows 8, both the RTM version.

Description

Like you can see in Creating portable code in Windows Store Apps (PCL + MVVM + OData Services), you have a Portable Class Library that has model and view model defined! Which has the following targts:

 

with this i conclude that code is portable and can be used in Windows Phone 7.5 or higher.

We can create the Windows Phone 8 App and Windows Phone 7.5 (with update for 7.8) App and use this code, let’s see how.

1. Start creating the Windows Phone ClientApp Project:

 

 

2. After this update the namespace and startup object to:

 

 

You can create the same for Windows Phone 7.5!

3. Install the MVVM Light (PCL) for each Windows Phone ClientApp project:

 

4. Install the Bcl.Async package

See more about it here Async for .NET Framework 4, Silverlight 4 and 5, and Windows Phone 7.5 and 8

 

5. Add OData Services

OData Services is not portable,  we need to add the Service metadata for each client app or create a separate project for it ( this is a sample, is not necessary and will add in client app).

The metadata used is :http://odata.netflix.com/v2/Catalog/. For understand that i did see Consuming Odata Service in Windows Store Apps (Include MVVM Pattern) is similar for Windows Phone.

 

6. Create these folders

  • Extensions
  • Services
  • Styles
  • View
  • ViewModel

in each Windows Phone ClientApp project, like this:

 

 

We created the same sctruture from Windows Store App!

Why?

Because make sense and is more simple to undestand all code and more important is because we will reuse code files from Windows Store Apps.

 

7. Use “Add as Link” for link all files that are inside the following folders:

  • Extensions
  • Services
  • ViewModel

 

the result will be

I linked three files that are physically contained inside the Windows Store Client App.

NOTE: Each linked file is unique, is not a copy from the original, each change will represent a change in all projects!

 

8 . Add the ViewModelLocator to the App.xaml

<viewModel:ViewModelLocator x:Key=”Locator”/>

If you compile the code, maybe you will find some old dependencies, because in “last refactoring” uses some using that weren´t delete. And because i created Netflix.ClientApp and NetFlix.ClientApp namespace, the F or f  made the name to different! Is not important, but is more easy if we keep the same names for that can be shared or similar.

These problems are common and I could create a sample and documentation without them, but i think is important to share it, because always happens to all devs! 🙂

After this we only need to create the view for show data, let’s do it:

9. Create the View, adding content to the page:

Before define the page, prepare the information you will need.

9.1. “Add as Link” the BooleanNegationConverter and BooleanToVisibilityConverter from Windows Store Apps:

 

9.2. Create the ResourceDictionary.xaml with datatemplates:

<!-- DataTemplates for MyTitleItemView  --> 
    <DataTemplate x:Key="MyTopDVDMoviesItemTemplate"> 
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Height="120"> 
            <Image  CacheMode="BitmapCache" Source="{Binding Item.Image}"   Width="82" Stretch="Uniform"  Margin="10,10,5,10"/> 
            <StackPanel  Margin="10,10,5,10"> 
                <TextBlock Text="{Binding Item.Name}" Foreground="{StaticResource ForegroundBrush}" TextWrapping="Wrap"  Margin="0,0,5,0"/> 
               <StackPanel Orientation="Vertical" Margin="0,0,10,0" > 
                    <TextBlock TextWrapping="Wrap"  Foreground="{StaticResource ForegroundBrush}"  Margin="0,0,0,5">Available: <Run  Text="{Binding Item.AvailableFrom,  StringFormat='\{0:d MMMM yyyy\}'}" /></TextBlock> 
                </StackPanel> 
            </StackPanel> 
        </StackPanel> 
    </DataTemplate> 

    <DataTemplate x:Key="MyNewDVDMoviesItemTemplate"> 
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"  Height="120"> 
            <Image  CacheMode="BitmapCache" Source="{Binding Item.Image}"   Width="82" Stretch="Uniform"  Margin="10,10,5,10"/> 
            <StackPanel  Margin="10,10,5,10"> 
                <TextBlock Text="{Binding Item.Name}" Foreground="{StaticResource ForegroundBrush}" TextWrapping="Wrap"  Margin="0,0,5,0"/> 
                <StackPanel Orientation="Horizontal" Margin="0,10,10,0"> 
                    <TextBlock  Margin="0,0,5,5" Text="Rating:" Foreground="{StaticResource ForegroundBrush}" /> 
                    <TextBlock  Margin="0,0,0,5" Text="{Binding Item.Rating}" Foreground="{StaticResource ForegroundBrush}"/> 
                </StackPanel> 
                <StackPanel Orientation="Vertical" Margin="0,0,10,0" > 
                    <TextBlock TextWrapping="Wrap"  Foreground="{StaticResource ForegroundBrush}"  Margin="0,0,0,5">Available: <Run  Text="{Binding Item.AvailableFrom,  StringFormat='\{0:d MMMM yyyy\}'}" /></TextBlock> 
                </StackPanel> 
            </StackPanel> 
        </StackPanel> 
    </DataTemplate>

9. Create inside the View folder the TitlePage.xaml:

<phone:PhoneApplicationPage 
    x:Class="Netflix.ClientApp.View.TitlesPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
    FontSize="{StaticResource PhoneFontSizeNormal}" 
    Foreground="{StaticResource PhoneForegroundBrush}" 
    SupportedOrientations="Portrait" Orientation="Portrait" 
    DataContext="{Binding TitlesViewModel, Source={StaticResource Locator}}" 
    mc:Ignorable="d" 
    shell:SystemTray.IsVisible="True"> 

    <!--LayoutRoot is the root grid where all page content is placed--> 
    <Grid x:Name="LayoutRoot" Background="#B9090B"> 
        <Grid.RowDefinitions> 
            <RowDefinition Height="Auto"/> 
            <RowDefinition Height="*"/> 
        </Grid.RowDefinitions> 

        <!--TitlePanel contains the name of the application and page title--> 
        <StackPanel Grid.Row="0" Margin="12,20,0,0"> 
            <TextBlock Text="MY NetFlix Catalog" Foreground="{StaticResource ForegroundBrush}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle2Style}"/> 
        </StackPanel> 

        <!--ContentPanel - place additional content here--> 
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,17,12,0"> 
            <ProgressBar IsIndeterminate="True" Height="20"  
                          Visibility="{Binding IsToShowProgress, Converter={StaticResource BooleanToVisibilityConverter}}" 
                         Foreground="{StaticResource ForegroundBrush}" IsEnabled="{Binding IsToShowProgress}" Margin=" 0,5,0,0"/> 

            <phone:Pivot> 
                <!--Pivot item one--> 
                <phone:PivotItem Header="TOP"> 
                    <ListBox Name="lbxTopTitles" ItemsSource="{Binding Groups[0].Items}" SelectionMode="Single"  ItemTemplate="{StaticResource MyTopDVDMoviesItemTemplate}" /> 
                </phone:PivotItem> 

                <!--Pivot item two--> 
                <phone:PivotItem Header="New"> 
                    <ListBox Name="lbxNewTitles"  ItemsSource="{Binding Groups[1].Items}" SelectionMode="Single" ItemTemplate="{StaticResource MyNewDVDMoviesItemTemplate}" /> 
                </phone:PivotItem> 
            </phone:Pivot> 
        </Grid> 
    </Grid> 

</phone:PhoneApplicationPage>

and

 public partial class TitlesPage 
    { 
        /// <summary> 
        /// Initializes a new instance of the <see cref="TitlesPage" /> class. 
        /// </summary> 
        public TitlesPage() 
        { 
            InitializeComponent(); 
        } 

        /// <summary> 
        /// Called when a page becomes the active page in a frame. 
        /// </summary> 
        /// <param name="e">An object that contains the event data.</param> 
        protected override async void OnNavigatedTo(NavigationEventArgs e) 
        { 
            var titlesViewModel = DataContext as TitlesViewModel; 
            if (titlesViewModel != null 
                && (e.NavigationMode == NavigationMode.New || e.NavigationMode == NavigationMode.Refresh)) 
            { 
                await titlesViewModel.LoadDataAsync(); 
            } 
        } 
     }

There is one point that is diferente from WP8 and WP7.5, is the namespace for pivot control.

XAML cannot be shared, better should´t!

9.4. Define the TitlesPage.xaml as a start page:

 

10. The output

 

 

 

Notes:

1. In inital sample, that was initial source, i did not change the namespace from Netflix.ClientApp to Netflix.PortableClassLibrar, but was because i forgot. You should be aware too. And i did not changed because i am creating a git repository for how wants to see the commit and changes i did.

2. If you want to see the commit and changes i did when i create this sample, visit the codeproject oficial reference, here:

 

Will be published soon!

 

Source Code Files

The solution has the following structure:

 

Details:

  • IServiceManager.cs has the IServiceManager interface and define the interface for the ServiceManager.
  • ServiceManager.cs has the ServiceManager class and it encapsulate the NetFlixService and exposes only the methods that is need in ViewModel.
  • FakeServiceManager.cs is the implementation of the IServiceManager, but is a fake data.
  • TitlesViewModel.cs has TitlesViewModel class and it is used for binding with the DataContext from TitlesPage.
  • ViewModelLocator.cs has the ViewModelLocator class that help to binding the view model with the view.
  • ViewModelHelper.cs has the ViewModelHelper class the helps to create grouped data.
  • TitlesPage.xaml and TitlesPage.xaml.cs that is the main page.
  • Templates.xaml is a resource dictionary that has the DataTemplate for the view.
  • NetFlixItemTemplateSelector.cs has the NetFlixItemTemplateSelector that is used for get the ItemTemplate for each item in gridView.

Others References

Run the sample

To debug the app and then run it, press F5 or use Debug > Start Debugging. To run the app without   debugging, press Ctrl+F5 or use Debug > Start Without Debugging.

 

More Information

Ask me on twitter @saramgsilva

[PT] Resumo e recursos do evento Windows 8 App Swipe

microsoft_21_janeiro

Eis o resumo de cada uma das sessões apresentadas no evento “App Swipe” a 21 de Janeiro de 2013 no auditório da Microsoft Portugal, bem como os links mais relevantes.

 

09:30 Introduction, Tools and Advertising // Tiago Andrade e Silva, Microsoft Portugal

Resumo: Nesta sessão será apresentado um resumo de ferramentas úteis para quem desenvolve Apps, bem como algumas dicas que não são óbvias de encontrar na documentação. Será também demonstrado como monetizar aplicações recorrendo ao Microsoft Ads SDK.

 

Recursos:

 

10:00 Multilanguage Toolkit // Emanuel Amiguinho, Microsoft Portugal

Resumo: Hoje em dia o alcance das aplicações é maior, logo tem de se ter em conta os targets bem como poder trazer a melhor experiência de utilizador para todos, para isso as apps devem estar em multilanguage.  Nesta sessão irei abordar como utilizar multilinguage toolkit nas aplicações, com o uso resources, privacy policies e outros aspetos necessários a correta implementação, tanto em C# como em Javascript.

 

Recursos:

Código fonte da solução apresentadada na sessão

Download do Multilanguage Toolkit: http://msdn.microsoft.com/en-us/windows/apps/hh848309.aspx

Translating UI Recourses (JS): http://msdn.microsoft.com/en-us/library/windows/apps/hh943060.aspx

Translating UI Recourses (C#): http://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh965329(v=win.10).aspx

How to use the Multilingual App Toolkit (JS): http://msdn.microsoft.com/en-us/library/windows/apps/jj569303.aspx

How to use the Multilingual App Toolkit (C#): http://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ572370(v=win.10).aspx

 

10:30 Registo e publicação de Apps na store // Pedro Serrano, Cavedigital

Resumo: O registo na Windows Store é o primeiro passo a dar para fazer chegar uma app ao resto do Mundo. Nesta sessão abordaremos os passos necessários para se registar e publicar uma app na Windows Store, sobrevivendo a tax profiles e outras zonas de desconforto para developers.

Recursos:

Requisitos de certificação na store: http://aka.ms/StoreReq

Como resolver questões de certificação: http://aka.ms/StoreFix

Problemas com a Store? http://aka.ms/StoreSupport

 

11:00 Coffee Break & NiceReader presentation // Filipe Clérigo, Viatecla

Resumo: A grande penetração no mercado de devices digitais, nomeadamente tablets dos vários fabricantes, exige soluções que permitam criar e distribuir informação interativa de forma eficiente. O Nicereder é uma solução completa de publishing digital, desde a criação de conteúdos à distribuição em múltiplas plataformas.

 

Recursos:

Apresentação do produto:

Informação, case studies e vídeo de demonstração

 

11:30 Pagamentos, inapp purchases, trial (time / feature) // Nelson João, Viatecla

Resumo: A monetização é um aspeto crucial de qualquer aplicação de e-commerce. O In-app Commerce no Windows 8 desempenha um papel fundamental na rentabilidade da aplicação.

Desenvolvendo uma aplicação Windows 8 (com XAML / C #) de raiz, vamos demonstrar o uso prático do ambiente de desenvolvimento CurrentAppSimulator e CurrentApp aplicado a alguns exemplos de In-app Commerce, como por exemplo, modo trial e compras in-app.

 

Recursos:

Source Code da App demo utilizada no evento

Trial app and in-app purchase sample

Validação de recibos e restauro de compras:

How to support in-app purchases (Windows)

 

12:00 Identidade em Windows 8 (Live SDK) // Tiago Barbosa, Microsoft Portugal

Resumo: Nesta sessão vou mostrar como integrar uma Windows Store App com o Live SDK. Começando por criar uma Windows Store App a partir do template do Visual Studio 2012 e integrar a mesma com o LiveSDK. Autenticar o utilizador e pedir autorização para aceder à informação do utilizador e ao Skydrive respectivo. Em seguida, vamos fazer a integração dos controlos Signin/Signout no charm de definições do Windows 8. E por fim, alterar a App de modo a que esta receba informação do Skydrive do utilizador.

 

Recursos:

Código fonte da Solução apresentada no evento

Live Connect documentation

Guidelines for the Microsoft account sign-in experience

 

12:30 Consumindo serviços OData em Windows 8 Store Apps // Sara Silva, Zon

Resumo: Esta demo tem como objetivo mostrar os passos necessários para consumir um serviço OData em Windows Store Apps. (C# / XAML)

 

Recursos:

Código fonte da solução apresentada na sessão

WCF Data Services Blog

WCF Data Services

OData 101: Building our first OData-based Windows Store app (Part 1)

OData 101: Building our first OData-based Windows Store app (Part 2)

 

 

14:30 Media Player Framework // Marco Silva, CreateIT

Resumo: As Windows 8 Store Apps são um novo modelo de aplicação disponibilizado com o Windows 8, adaptadas a dispositivos tácteis e tablets. Neste tipo de aplicações, o suporte a experiências ricas de multimédia é requisito especialmente importante para a implementação de aplicações na área de media.

 

Esta sessão apresenta os conceitos base e tecnologias de suporte ao desenvolvimento de aplicações Windows 8 (Store Apps) que integram vídeo e áudio. Será implementada e demonstrada uma aplicação tipo que integra um player de vídeo.

 

Recursos:

Código fonte da solução apresentada na sessão

Building a rich and extensible media platform

Building video application on Windows 8 – things you want to know

Player Framework: an open source component of the Microsoft Media Platform

 

15:00 Bing Maps // Ricardo Pinto, Agap2

Resumo: Introdução às funcionalidades principais providenciadas pelos serviços REST dos Bing Maps, com foco no cálculo de rotas e informação de trânsito.

 

Recursos:

Código fonte da solução apresentada na sessão

Bing Maps SDK for Windows Store apps

Add Bing Maps to a Windows Store app

Bing Maps SDK for Windows Store apps Samples

Bing Maps Portal

 

15:30 Local Storage and caching / Making your app work offline, detecting offline mode, caching sets of data // Ricardo Pinto, Agap2

Resumo: Introdução à API de Storage das aplicações Windows 8, com foco na elaboração de uma camada de serialização e de persistência local de objectos.

 

Recursos:

Código fonte da solução apresentada na sessão

 

16:00 Coffee Break & 3D printing // Francisco Mendes, Bitbox

Resumo: Impressão 3D é sem dúvida a grande novidade que abre um leque muito interessante de possibilidades. Nesta sessão

 

Recursos:

http://www.bitbox.pt

http://www.reprap.org/wiki/RepRap

http://www.3dprinting-r2c2.com/

http://www.thingiverse.com/

http://www.openscad.org/

Nokia 3D Printing Development Kit Announced For Lumia 820

 

16:30 Typescript // Alexandre Marreiros, Innovagency

Resumo: TypeScript is a language for application-scale JavaScript development.

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.

Any browser. Any host. Any OS. Open Source.

 

Recursos:

Código fonte da solução apresentadada na sessão

http://www.typescriptlang.org/

TypeScript Templates for Windows 8

 

17:00 Azure Mobile Services (Identity, WPS…) // Nuno Silva, Microsoft Portugal

Resumo: As melhores aplicações estão ligadas à cloud. Esta sessão mostra como utilizar os Windows Azure Mobile Services, que de forma simples, permite que aplicações Windows 8, Windows Phone e até iOS possam guardar e ler informação na cloud, autenticar os utilizadores, enviar push notifications e correr lógica server-side. Isto permite construir uma experiência consistente em múltiplas plataformas e dispositivos, sem ser necessário qualquer conhecimento prévio de Azure.

 

Recursos:

Windows Azure Training Kit

A Demo apresentada no evento está incluída no training kit (Demos -> Building Block Services -> Event Buddy)

17:30 Code Sharing (WP+WP8) // Nuno Silva, Microsoft Portugal

Resumo: Esta sessão demonstra diversas técnicas para partilhar/portar código entre aplicações Windows Phone e Windows 8. São usadas técnicas como MVVM, Linked Files, Conditional Compilation e Portable Class Libraries com e sem Dependency Injection.

 

Recursos:

Código fonte da solução apresentadada na sessão

Developing an End-to-End Windows Store app using C++ and XAML: Hilo

p&p

Patterns & Practices has released Hilo guidance: Developing a Windows Store app using C++ and XAML which is part of the Windows SDK.

Table of contents at a glance

Here are the major topics in this guide. For the full table of contents, see Hilo table of contents.

Consuming Odata Service in Windows Store Apps (Include MVVM Pattern)

Introduction

This demo has the main goal to show the steps that is need to consuming an OData service in Windows Store Apps, and use the MVVM Pattern and has Ioc container for manage the dependencies.

Get the sample here.

Building the Sample

You only need Visual Studio 2012 and Windows 8, both the RTM version.

Description

For concretizate this sample i used the Netflix OData Catalog API (Preview), that can be found where:

For who is starting with OData service in Windows Store Apps i recommend to install the:

WCF Data Services Tools for Windows Store Apps

“The WCF Data Services Tools for Windows Store Apps installer extends the Add Service Reference experience with client-side OData support for Windows Store Apps in Visual Studio 2012.”

Here is the main points:

1. Creating a Blank Project like you can see in the following image:

2. Add Service Reference

3. Analizing the NetflixService

4. The IServiceManager, FakeServiceManager and ServiceManager

4.1. The LoadNewDVDMoviesAsync method

4.2. The LoadTopDVDMoviesAsync method

4.3. The DataServiceContextAsyncExtension

4.4 The model

5. The TitlesViewModel

5.1 The LoadDataAsync method

5.2 The GroupView and ItemView

6. Binding the view model with the view

6.1. ViewModelLocator

6.2. In App.xaml

6.3. In the TitlesPage.xaml

6.4. In the TitlesPage.xaml.cs

6.5. Binding Data

7. The output / running the demo

8. Fiddler


Let’s start:

1. Creating a Blank Project like you can see in the following image:

new project image

Note: I used te name Netflix.ClientApp (Win8) for the project, but i will change the namespace for Netflix.ClientApp and in the future if I need to create the Netflix.ClientApp (WP8,  i can use the same namespace and if need to “linked as” some file i will not have problems with namespaces.

2. Add Service Reference

add reference

add metadata

The service reference that i added is: http://odata.netflix.com/v2/Catalog/

3. Analizing the NetflixService

The result will be:
add reference

Note: Is not required, but you can create a class diagram that will show all classes and its properties, method and events. It helps to understand that was added when you added the service reference.
class diagram
4. The IServiceManager, FakeServiceManager and the ServiceManager

Now the project has the service, and I decided to get the top of the DVD Movies and the new releases of the DVD Movies. With this i will define an interface for my service manager.

Here is the code:

 /// <summary> 
    /// Defines the service manager interface 
    /// </summary> 
    public interface IServiceManager 
    { 
        /// <summary> 
        /// Loads the new dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return a IEnumerable. 
        /// </returns> 
        Task<IEnumerable> LoadNewDVDMoviesAsync(); 

        /// <summary> 
        /// Loads the top dvd movies async. 
        /// </summary> 
        /// <returns>Represents an asynchronous operation that return a IEnumerable.</returns> 
        Task<IEnumerable> LoadTopDVDMoviesAsync(); 
    }

The fake implementation will be

FakeServiceManager

/// <summary> 
    /// The fake service manager. 
    /// </summary> 
    public class FakeServiceManager : IServiceManager 
    { 
        /// <summary> 
        /// The bitmap soure 
        /// </summary> 
        private readonly BitmapImage _bitmapSoure; 

        /// <summary> 
        /// Initializes a new instance of the <see cref="FakeServiceManager" /> class. 
        /// </summary> 
        public FakeServiceManager() 
        { 
           _bitmapSoure = new BitmapImage(new Uri("ms-appx:///Images/FakeImage.png")); 
        } 

        /// <summary> 
        /// Creates the items. 
        /// </summary> 
        /// <param name="number">The number.</param> 
        /// <returns>the list of mytitles</returns> 
        public IEnumerable CreateItems(int number) 
        { 
            var myTitles = new List<MyTitle>(); 
            for (var i = 0; i < number; i++) 
            { 
                myTitles.Add(new MyTitle 
                        { 
                            Name = string.Concat("Fake Name ", i), 
                            AvailableFrom = DateTime.Now, 
                            Rating = 0, 
                            Image = _bitmapSoure 
                        }); 
            } 

            return myTitles; 
        } 

        /// <summary> 
        /// Loads the new dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return an IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadNewDVDMoviesAsync() 
        { 
            return await Task.Run(() => CreateItems(20)); 
        } 

        /// <summary> 
        /// Loads the top dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return an IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadTopDVDMoviesAsync() 
        { 
            return await Task.Run(() => CreateItems(20)); 
        } 
    }

The implementation for the real service will be

ServiceManager

public class ServiceManager : IServiceManager 
    { 
        /// <summary> 
        /// The _netflix catalog. 
        /// </summary> 
        private readonly NetflixCatalog _netflixCatalog; 

        /// <summary> 
        /// Initializes a new instance of the <see cref="ServiceManager"/> class. 
        /// </summary> 
        public ServiceManager() 
        { 
            _netflixCatalog = new NetflixCatalog(new Uri("http://odata.netflix.com/v2/Catalog/"), UriKind.Absolute); 
        } 

        /// <summary> 
        /// Loads the new dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return a IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadNewDVDMoviesAsync() 
        { 
            var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where(title => title.ReleaseYear >= 2012 
                                                                            && title.Dvd.Available 
                                                                            && title.Type == "Movie") 
                                                                       .OrderByDescending(item => item.Dvd.AvailableFrom) 
                                                                       .Take(30)).Expand(item => item.Genres).Expand(item => item.Directors); 
            var result = await query.ExecuteAsync(); 

            return ConvertToMyTitles(result); 
        } 

        /// <summary> 
        /// Loads the top dvd movies async. 
        /// </summary> 
        /// <returns> 
        /// Represents an asynchronous operation that return a IEnumerable. 
        /// </returns> 
        public async Task<IEnumerable> LoadTopDVDMoviesAsync() 
        { 
            var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where(title => title.ReleaseYear >= 2012 
                                                                                        && title.Dvd.Available 
                                                                                        && title.Type == "Movie") 
                                                                         .OrderByDescending(item => item.AverageRating) 
                                                                         .Take(20)).Expand(item => item.Genres).Expand(item => item.Directors); 
            var result = await query.ExecuteAsync(); 

            return ConvertToMyTitles(result); 
        } 

        /// <summary> 
        /// Converts to my titles. 
        /// </summary> 
        /// <param name="titles">The titles.</param> 
        /// <returns>The my titles list.</returns> 
        private IEnumerable ConvertToMyTitles(IEnumerable<Title> titles) 
        { 
            return 
                titles.Select( 
                    title => 
                    new MyTitle 
                    { 
                        Name = title.Name, 
                        Image = new BitmapImage(new Uri(title.BoxArt.MediumUrl)), 
                        AvailableFrom = title.Dvd.AvailableFrom, 
                        Rating = title.AverageRating 
                    }).ToList(); 
        } 
    }

Here, there are two importante methods:

  • LoadNewDVDMoviesAsync
  • LoadTopDVDMoviesAsync

4.1. The LoadNewDVDMoviesAsync method

First i will create the query that will be used for the service request:

  var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where( 
title => title.ReleaseYear >= 2012 &&  
title.Dvd.Available && 
title.Type == MovieStringValue) 
.OrderByDescending(item => item.Dvd.AvailableFrom) 
.Take(30)) 
.Expand(item => item.Genres) 
.Expand(item => item.Directors);

Here, I want all title that release year is greater than 2012 and DVD is available and type is Movie and i want these title order by data from dvd is available. At the end i only want the first 30 items and i want with Genres and Directors filled.

4.2. The LoadTopDVDMoviesAsync method

In this method the query will be:

var query = ((DataServiceQuery<Title>)_netflixCatalog.Titles.Where( 
title => title.ReleaseYear >= 2012 &&  
title.Dvd.Available && 
 title.Type == MovieStringValue) 
.OrderByDescending(item => item.AverageRating) 
.Take(20)) 
.Expand(item => item.Genres) 
.Expand(item => item.Directors);

Here, I want all title that release year is greater than 2012 and DVD is available and type is Movie and i want these title order by average rating. At the end i only want the first 20 items and i want with Genres and Directors properties filled.

4.3. The DataServiceContextAsyncExtensions

Inside the both methods i will execute the query like this:

var result = await query.ExecuteAsync();

and it will do a call to the server and request the data.

For simplicate the calls i added DataServiceContextAsyncExtension that allow to use the async and await keyworks.

 /// <summary> 
    /// Defines the DataServiceContext Async Extensions 
    /// </summary> 
    public static class DataServiceContextAsyncExtensions 
    { 
        /// <summary> 
        /// Executes the async. 
        /// </summary> 
        /// <typeparam name="TResult">The type of the result.</typeparam> 
        /// <param name="query">The query.</param> 
        /// <returns>the task of the enumerable of the type TResult</returns> 
        public static async Task<IEnumerable<TResult>> ExecuteAsync<TResult>(this DataServiceQuery<TResult> query) 
        { 
            return await Task.Factory.FromAsync<IEnumerable<TResult>>(query.BeginExecute(null, null), query.EndExecute); 
        } 
    }

4.4 The Model

Here is the class diagram:

GroupView is used to group a list of itemview that can have a MyTitle or Title object ( dependes if your view dependents of the service data or not, if yes when there is an update you maybe need to udpate the view and the viewmodel if not, you only need to update the ConvertToMyTitles method in ServiceManager.

Note: This solution is good when you have for example:

Group 1 with a list of A data type elements and a Group 2 with a list of B data type elements.

You only need create a class similar i do with MyTitleItemView or TitleItemView and the binding as easy and only need to define one ItemTemplateSelector that will choose the correct DataTemplate (normally by data type or group when both groups has the same data type).

5. The TilesViewModel

Because I am using the MVVM pattern, I will call theses methods in my view model, i could implement it inside of the view model but i don´t want have dependencies in my view model.

In the view model i will have:

 /// <summary> 
        /// Initializes a new instance of the <see cref="TitlesViewModel"/> class.  
        /// </summary> 
        /// <param name="serviceManager"> 
        /// The service Manager. 
        /// </param> 
        /// <param name="navigationService"> 
        /// The navigation Service. 
        /// </param> 
        public TitlesViewModel(IServiceManager serviceManager, INavigationService navigationService) 
        { 
            IsToShowProgress = true; 
            _serviceManager = serviceManager; 
            _navigationService = navigationService; 
        }

and inside the LoadDataAsync i will have:

public async Task LoadDataAsync() 
        { 
            IsToShowProgress = true; 

            try 
            { 
                var newDVDMovies = _serviceManager.LoadNewDVDMoviesAsync(); 
                var topDVDMovies = _serviceManager.LoadTopDVDMoviesAsync(); 

                await Task.WhenAll(new Task[] { newDVDMovies, topDVDMovies }); 

                if (newDVDMovies.IsCompleted && topDVDMovies.IsCompleted) 
                { 
                    Groups = new List<GroupView> 
                                 { 
                                     ViewModelHelper.GetGroupView(NameDefinitions.TopDVDMoviesId, NameDefinitions.TopDVDMoviesLabel, topDVDMovies.Result), 
                                     ViewModelHelper.GetGroupView(NameDefinitions.NewDVDMoviesId, NameDefinitions.NewDVDMoviesLabel, newDVDMovies.Result) 
                                 }; 
                } 
                else 
                { 
                    ErrorMessage = GetErrorMessage(newDVDMovies, topDVDMovies); 
                } 

                IsToShowProgress = false; 
            } 
            catch (Exception exception) 
            { 
                IsToShowProgress = false; 

                // TODO: Define a better message error for the user 
                ErrorMessage = exception.Message; 
            } 
        }

Here, is important to refer that i will do two service requests in the same time and will wait until the both are finish, this is great because i don´t need to request one by one and the time spent with the request is maximun of the both.

6. Binding the view model with the view

 

6.1. ViewModelLocator

 

This class continas the SimpleIoc for dependecy injection and helps to binding the view model with the view.

/// <summary> 
    /// This class contains static references to all the view models in the 
    /// application and provides an entry point for the bindings. 
    /// </summary> 
    public class ViewModelLocator 
    { 
        /// <summary> 
        /// Initializes a new instance of the ViewModelLocator class. 
        /// </summary> 
        public ViewModelLocator() 
        { 
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 

            if (!SimpleIoc.Default.IsRegistered<IServiceManager>()) 
            { 
                // For use the fake data do: 
                // SimpleIoc.Default.Register<IServiceManager, FakeServiceManager>(); 
                SimpleIoc.Default.Register<IServiceManager, ServiceManager>(); 
            } 

            SimpleIoc.Default.Register<TitlesViewModel>(); 
        } 

        /// <summary> 
        /// Gets the titles view model. 
        /// </summary> 
        public TitlesViewModel TitlesViewModel 
        { 
            get 
            { 
                return ServiceLocator.Current.GetInstance<TitlesViewModel>(); 
            } 
        } 
    }

6.2. In App.xaml

<viewModel:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />

6.3. In the TitlesPage.xaml

DataContext="{Binding TitlesViewModel, Source={StaticResource Locator}}"

Here is defined the DataContext and with this all the page can be binding to the view model.

6.4. In the TitlesPage.xaml.cs:

 

         /// <summary> 
        /// Invoked when this page is about to be displayed in a Frame. 
        /// </summary> 
        /// <param name="e">Event data that describes how this page was reached.  The Parameter 
        /// property is typically used to configure the page.</param> 
        protected override async void OnNavigatedTo(NavigationEventArgs e) 
        { 
            if (_titlesViewModel != null) 
            { 
                await _titlesViewModel.LoadDataAsync(); 
            } 
        }

Here is the moment the view model will load the data.

6.5 Binding Data

In TitlesPage.xaml i have a CollectionViewSource the allow to defined a what is the source and in grouped data which are the path of the Items.

<CollectionViewSource 
            x:Name="GroupedItemsViewSource" 
            Source="{Binding Groups}" 
            IsSourceGrouped="true" 
            ItemsPath="Items" 
            d:Source="{Binding Groups}"/>

This will help to group data in GridView.

<GridView 
                x:Name="ItemGridView"                              AutomationProperties.AutomationId="ItemGridView" 
                AutomationProperties.Name="Grouped Items" 
                Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" 
                Visibility="{Binding IsToShowProgress, Converter={StaticResource NagationBooleanToVisibilityConverter}}" 
                Padding="116,0,40,46" 
                IsSwipeEnabled="True" 
                IsItemClickEnabled="True" 
                ItemClick="ItemGridViewOnItemClick" 
                ItemsSource="{Binding Source={StaticResource GroupedItemsViewSource}}" 
                ItemTemplateSelector="{StaticResource NetFlixItemTemplateSelector}" 
                SelectionMode="Single" ItemContainerStyle="{StaticResource GridViewItemStyle}"> 
                <GridView.ItemsPanel> 
                        <ItemsPanelTemplate> 
                            <VirtualizingStackPanel Orientation="Horizontal"> 
                                <VirtualizingStackPanel.ChildrenTransitions> 
                                    <TransitionCollection> 
                                        <EntranceThemeTransition /> 
                                        <RepositionThemeTransition /> 
                                    </TransitionCollection> 
                                </VirtualizingStackPanel.ChildrenTransitions> 
                            </VirtualizingStackPanel> 
                        </ItemsPanelTemplate> 
                    </GridView.ItemsPanel> 
                <GridView.GroupStyle> 
                    <GroupStyle> 
                        <GroupStyle.HeaderTemplate> 
                            <DataTemplate> 
                                <Grid Margin="1,0,0,6"> 
                                    <Button 
                                        AutomationProperties.Name="Group Title" 
                                        Style="{StaticResource TextPrimaryButtonStyle}" > 
                                        <StackPanel Orientation="Horizontal"> 
                                            <TextBlock Text="{Binding Label}" 
                                                       Margin="3,-7,10,10" 
                                                       Style="{StaticResource GroupHeaderTextStyle}" /> 
                                            <TextBlock Text="{StaticResource ChevronGlyph}"  
                                                       FontFamily="Segoe UI Symbol"  
                                                       Margin="0,-7,0,10"  
                                                       Style="{StaticResource GroupHeaderTextStyle}"/> 
                                        </StackPanel> 
                                    </Button> 
                                </Grid> 
                            </DataTemplate> 
                        </GroupStyle.HeaderTemplate> 
                        <GroupStyle.Panel> 
                            <ItemsPanelTemplate> 
                                <VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,80,0"/> 
                            </ItemsPanelTemplate> 
                        </GroupStyle.Panel> 
                    </GroupStyle> 
                </GridView.GroupStyle> 
            </GridView>

And the

<templateSelector:NetFlixItemTemplateSelector x:Key="NetFlixItemTemplateSelector"/>

will help to define the ItemTemplate that will be apply in each group.

Each item data template is defined in Template.xaml

<DataTemplate x:Key="TopDVDMoviesItemTemplate"> 
        <Grid HorizontalAlignment="Left" Width="82" Height="120" Background="#B9090B"> 
            <Image Source="{Binding Item.BoxArt.MediumUrl}"  Width="82" Height="120"  CacheMode="BitmapCache" Stretch="Uniform" /> 
        </Grid> 
    </DataTemplate> 

    <DataTemplate x:Key="NewDVDMoviesItemTemplate"> 
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Width="300" Height="120"> 
            <Image  CacheMode="BitmapCache" Source="{Binding Item.BoxArt.MediumUrl}"   Width="82" Stretch="Uniform"  Margin="10,10,5,10"/> 
            <StackPanel  Margin="10,10,5,10"> 
                <TextBlock Text="{Binding Item.Name}" TextWrapping="Wrap"  Margin="0,0,5,0"/> 
                <StackPanel Orientation="Horizontal" Margin="0,10,10,0"> 
                    <TextBlock  Margin="0,0,5,5" Text="Rating:" /> 
                    <TextBlock  Margin="0,0,0,5" Text="{Binding Item.AverageRating}" /> 
                </StackPanel> 
                <StackPanel Orientation="Vertical" Margin="0,0,10,0" > 
                    <TextBlock  Margin="0,0,0,5" Text="Available:"  /> 
                    <TextBlock Text="{Binding Item.Dvd.AvailableFrom,  
                                                   Converter={StaticResource StringFormatConverter}, ConverterParameter=\{0:d MMMM yyyy\}}"  
                                                   TextWrapping="Wrap"  /> 
                </StackPanel> 
            </StackPanel> 
        </StackPanel> 
    </DataTemplate>

7. The output/ running the demo

 

The result of the TitlesPage is:

 

8. Fiddler

In fiddler we can see the service requests:

GET

/v2/Catalog/Titles()?$filter=ReleaseYear%20ge%202012%20and%20Dvd/Available%20and%20Type%20eq%20’Movie’&$orderby=Dvd/AvailableFrom%20desc&$top=30&$expand=Genres,Directors

HTTP/1.1

GET

/v2/Catalog/Titles()?$filter=ReleaseYear%20ge%202012%20and%20Dvd/Available%20and%20Type%20eq%20’Movie’&$orderby=AverageRating%20desc&$top=20&$expand=Genres,Directors

HTTP/1.1

 

Notes:

for use Fiddler with Windows 8 Store Apps is required the Win8 config installed.

See the Fiddler Extensions.

Others Notes:

1. Because i am using MVVM Light, from this library i used:

  • A ViewModelBase class to be used as the base class for ViewModels.
  • A ViewModelLocator class that comes with MVVM – Light serves two purposes:

1 .It allows you to locate your ViewModel from inside your XAML and hook it to the DataContext.

2. It allows you to control two different ViewModels:  a design time view model, and a run time ViewModel.   Because one of the author’s goals of MVVM – Light is to make your XAML – ViewModel connection visibile in blend (or ‘blendable’) ,   the ViewModelLocator comes in handy for this purpose.

  • A SimpleIoc is a simple container for dependency injection.

For more about MVVM Light see http://mvvmlight.codeplex.com/

(It is not the unique solution)

2. Because this is a demo, maybe there is some points related with UI that is not completed, I focused in the propose of the sample. In the future i would like to work more in this sample and implement more sample using this sample.

Source Code Files

The solution has the following structure:

Details:

  • IServiceManager.cs has the IServiceManager interface and define the interface for the ServiceManager.
  • ServiceManager.cs has the ServiceManager class and it encapsulate the NetFlixService and exposes only the methods that is need in ViewModel.
  • FakeServiceManager.cs is the implementation of the IServiceManager, but is a fake data.
  • TitlesViewModel.cs has TitlesViewModel class and it is used for binding with the DataContext from TitlesPage.
  • ViewModelLocator.cs has the ViewModelLocator class that help to binding the view model with the view.
  • ViewModelHelper.cs has the ViewModelHelper class the helps to create grouped data.
  • TitlesPage.xaml and TitlesPage.xaml.cs that is the main page.
  • Templates.xaml is a resource dictionary that has the DataTemplate for the view.
  • NetFlixItemTemplateSelector.cs has the NetFlixItemTemplateSelector that is used for get the ItemTemplate for each item in gridView.

More Information

Run the sample

To debug the app and then run it, press F5 or use Debug > Start Debugging. To run the app without   debugging, press Ctrl+F5 or use Debug > Start Without Debugging.

More Information

Ask me on twitter @saramgsilva

 

Oficial Source:

http://code.msdn.microsoft.com/windowsapps/Consuming-Odata-Service-in-a97758e5

 

Listview header with the same listview’s width [XAML]

Today i found a question in forum that is related with the fact when we have a child control that need to have the same size from the parent.

The tip for this kind of problems is bingind the Height or Width property from child control with the ActualHeight or ActualWidth from parent.
Something like i said in that question.

 <ListView Background="Gold" Name="listview">
      <ListView.Header>
        <StackPanel Background="Red" Width="{Binding ActualWidth, ElementName=listview}">
           <TextBlock Text="ListView header"/>
         </StackPanel>
      </ListView.Header>

 </ListView>

The header of Listview has the auto size but if you binding the Width property to the ActualWidth form the ListView you will sure that the both has the same size!

See this test:

   <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ListView Background="Gold" Grid.Row="0">
            <ListView.Header>
                <StackPanel Background="Red">
                    <TextBlock Text="ListView with auto size header."/>
                </StackPanel>
            </ListView.Header>
        </ListView>

        <ListView Background="Gold" Name="listview" Grid.Row="2">
            <ListView.Header>
                <StackPanel Background="Red" Width="{Binding ActualWidth, ElementName=listview}">
                    <TextBlock Text="ListView with header that has the same Listview's Width"/>
                </StackPanel>
            </ListView.Header>
        </ListView>
    </Grid>

UPDATE:

Please read the comments to understand one important point about it!