Part 3 Complete code (Windows Store apps using C#/VB and XAML)

Applies to Windows only

This topic provides the complete code sample used in the tutorial Part 3: Navigation, layout, and views.

Important  This tutorial is intended for use with Microsoft Visual Studio 2013 and Windows 8.1. Parts of it will not work correctly with Microsoft Visual Studio 2012 and Windows 8.

This topic contains these sections:

Download location

This sample is not available for download.

Technologies

Programming languagesC#, Visual Basic .NET
Programming modelsWindows Runtime

Requirements

Minimum supported clientWindows 8.1
Minimum supported serverWindows Server 2012 R2
Minimum required SDKMicrosoft Visual Studio Express 2012 for Windows 8

View the code (XAML)

App.xaml

App.xaml contains only generated code.

App.xaml.cs/vb

App.xaml.cs/vb is unchanged from Part 2.

MainPage.xaml



<Page
    x:Name="pageRoot"
    x:Class="HelloWorld.MainPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld"
    xmlns:common="using:HelloWorld.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">Hello, world!</x:String>
        <Style x:Key="BigGreenTextStyle" TargetType="TextBlock">
            <Setter Property="Foreground" Value="Green"/>
            <Setter Property="FontSize" Value="36"/>
            <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
            <Setter Property="TextTrimming" Value="CharacterEllipsis"/>
            <Setter Property="TextWrapping" Value="Wrap"/>
            <Setter Property="Typography.StylisticSet20" Value="True"/>
            <Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
            <Setter Property="Typography.CaseSensitiveForms" Value="True"/>
            <Setter Property="LineStackingStrategy" Value="BlockLineHeight"/>
            <Setter Property="TextLineBounds" Value="TrimToBaseline"/>
            <Setter Property="OpticalMarginAlignment" Value="TrimSideBearings"/>
        </Style>
    </Page.Resources>
    <Page.TopAppBar>
        <CommandBar>
            <AppBarButton Label="AppBarButton" Icon="Pictures" Click="PhotoPageButton_Click"/>
        </CommandBar>
    </Page.TopAppBar>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>

        <StackPanel Grid.Row="1" Margin="120,30,0,0">
            <TextBlock Text="What's your name?" Style="{ThemeResource BaseTextBlockStyle}"/>
            <StackPanel Orientation="Horizontal" Margin="0,20,0,20">
                <TextBox x:Name="nameInput" Width="300" HorizontalAlignment="Left" TextChanged="NameInput_TextChanged"/>
                <Button Content="Say &quot;Hello&quot;" Click="Button_Click"/>
            </StackPanel>
            <TextBlock x:Name="greetingOutput" Style="{StaticResource BigGreenTextStyle}"/>
            <!--<Button Content="Go to photo page" Click="PhotoPageButton_Click"/>-->
        </StackPanel>
    </Grid>
</Page>

MainPage.xaml.cs/vb



using HelloWorld.Common;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

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

namespace HelloWorld
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }


        public MainPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            // Restore values stored in session state.
            if (e.PageState != null && e.PageState.ContainsKey("greetingOutputText"))
            {
                greetingOutput.Text = e.PageState["greetingOutputText"].ToString();
            }


            // Restore values stored in app data.
            Windows.Storage.ApplicationDataContainer roamingSettings =
                Windows.Storage.ApplicationData.Current.RoamingSettings;
            if (roamingSettings.Values.ContainsKey("userName"))
            {
                nameInput.Text = roamingSettings.Values["userName"].ToString();
            }
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            e.PageState["greetingOutputText"] = greetingOutput.Text;

        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            greetingOutput.Text = "Hello, " + nameInput.Text + "!";
        }

        private void NameInput_TextChanged(object sender, TextChangedEventArgs e)
        {
            Windows.Storage.ApplicationDataContainer roamingSettings =
                Windows.Storage.ApplicationData.Current.RoamingSettings;
            roamingSettings.Values["userName"] = nameInput.Text;
        }

        private void PhotoPageButton_Click(object sender, RoutedEventArgs e)
        {
            // Add this code.
            if (this.Frame != null)
            {
                this.Frame.Navigate(typeof(PhotoPage));
            }
        }
    }
}


PhotoPage.xaml



<Page
    x:Name="pageRoot"
    x:Class="HelloWorld.PhotoPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:HelloWorld"
    xmlns:common="using:HelloWorld.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" NavigationCacheMode="Enabled"
    SizeChanged="PhotoPage_SizeChanged">

    <Page.Resources>
        <common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">Hello, photo!</x:String>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ChildrenTransitions>
            <TransitionCollection>
                <EntranceThemeTransition/>
            </TransitionCollection>
        </Grid.ChildrenTransitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Back button and page title -->
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <AppBarButton x:Name="backButton" Icon="Back" Height="95" Margin="10,46,10,0"
                          Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" 
                          Visibility="{Binding IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource Mode=Self}}"
                          AutomationProperties.Name="Back"
                          AutomationProperties.AutomationId="BackButton"
                          AutomationProperties.ItemType="Navigation Button"/>
            <TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1" 
                       IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
        </Grid>
        <Grid x:Name="contentGrid" Grid.Row="1" Margin="120,0,0,120">
            <Grid.RowDefinitions>
                <RowDefinition Height="50"/>
                <RowDefinition Height="70"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Button Content="Get photo"/>
            <TextBlock Grid.Row="1" TextWrapping="Wrap" Text="TextBlock" Style="{ThemeResource SubheaderTextBlockStyle}"/>
            <StackPanel x:Name="imagePanel" Grid.Row="2" Orientation="Horizontal">
                <Border BorderBrush="Gray" BorderThickness="1" Background="Gray">
                    <Image x:Name="displayImage" Source="Assets/Logo.png"/>
                </Border>
                <StackPanel Margin="20,0,0,0">
                    <TextBlock TextWrapping="Wrap" Text="File name:" 
                               Style="{ThemeResource CaptionTextBlockStyle}"/>
                    <TextBlock TextWrapping="Wrap" Text="TextBlock" 
                               Style="{ThemeResource BodyTextBlockStyle}" Margin="10,0,0,30"/>
                    <TextBlock TextWrapping="Wrap" Text="Path:" 
                               Style="{ThemeResource CaptionTextBlockStyle}"/>
                    <TextBlock TextWrapping="Wrap" Text="TextBlock" 
                               Style="{ThemeResource BodyTextBlockStyle}" Margin="10,0,0,30"/>
                    <TextBlock TextWrapping="Wrap" Text="Date created:" 
                               Style="{ThemeResource CaptionTextBlockStyle}"/>
                    <TextBlock TextWrapping="Wrap" Text="TextBlock" 
                               Style="{ThemeResource BodyTextBlockStyle}" Margin="10,0,0,30"/>
                </StackPanel>
            </StackPanel>
        </Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState x:Name="DefaultLayout">
                    <Storyboard>
                    </Storyboard>
                </VisualState>

                <VisualState x:Name="PortraitLayout">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(StackPanel.Orientation)" 
                                                       Storyboard.TargetName="imagePanel">
                            <DiscreteObjectKeyFrame KeyTime="0">
                                <DiscreteObjectKeyFrame.Value>
                                    <Orientation>Vertical</Orientation>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" 
                                                       Storyboard.TargetName="imagePanel">
                            <DiscreteObjectKeyFrame KeyTime="0">
                                <DiscreteObjectKeyFrame.Value>
                                    <Thickness>0,0,20,0</Thickness>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>
</Page>


PhotoPage.xaml.cs/vb


using HelloWorld.Common;
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

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

namespace HelloWorld
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class PhotoPage : Page
    {
        private NavigationHelper navigationHelper;
        private ObservableDictionary defaultViewModel = new ObservableDictionary();

        /// <summary>
        /// This can be changed to a strongly typed view model.
        /// </summary>
        public ObservableDictionary DefaultViewModel
        {
            get { return this.defaultViewModel; }
        }

        /// <summary>
        /// NavigationHelper is used on each page to aid in navigation and 
        /// process lifetime management
        /// </summary>
        public NavigationHelper NavigationHelper
        {
            get { return this.navigationHelper; }
        }

        public PhotoPage()
        {
            this.InitializeComponent();
            this.navigationHelper = new NavigationHelper(this);
            this.navigationHelper.LoadState += navigationHelper_LoadState;
            this.navigationHelper.SaveState += navigationHelper_SaveState;
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
        }

        #region NavigationHelper registration

        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// 
        /// Page specific logic should be placed in event handlers for the  
        /// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
        /// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method 
        /// in addition to page state preserved during an earlier session.

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            navigationHelper.OnNavigatedFrom(e);
        }

        #endregion

        void PhotoPage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.NewSize.Height / e.NewSize.Width >= 1)
            {
                VisualStateManager.GoToState(this, "PortraitLayout", true);
            }
            else
            {
                VisualStateManager.GoToState(this, "DefaultLayout", true);
            }
        }
    }
}

 

 

Show:
© 2014 Microsoft