Part 4 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 4: File access and pickers.

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

MainPage.xaml is unchanged from Part 3.

MainPage.xaml.cs/vb

MainPage.xaml.cs/vb is unchanged from Part 3.

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" Click="GetPhotoButton_Click"/>
            <TextBlock Grid.Row="1" TextWrapping="Wrap" Text="{Binding DisplayName}" 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="{Binding Name}" 
                               Style="{ThemeResource BodyTextBlockStyle}" Margin="10,0,0,30"/>
                    <TextBlock TextWrapping="Wrap" Text="Path:"
                               Style="{ThemeResource CaptionTextBlockStyle}"/>
                    <TextBlock TextWrapping="Wrap" Text="{Binding Path}"
                               Style="{ThemeResource BodyTextBlockStyle}" Margin="10,0,0,30"/>
                    <TextBlock TextWrapping="Wrap" Text="Date created:" 
                               Style="{ThemeResource CaptionTextBlockStyle}"/>
                    <TextBlock TextWrapping="Wrap" Text="{Binding DateCreated.Date}"
                               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

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

''' <summary>
''' A basic page that provides characteristics common to most applications.
''' </summary>
Public NotInheritable Class PhotoPage
    Inherits Page

    Private mruToken As String = Nothing

    ''' <summary>
    ''' NavigationHelper is used on each page to aid in navigation and 
    ''' process lifetime management
    ''' </summary>
    Public ReadOnly Property NavigationHelper As Common.NavigationHelper
        Get
            Return Me._navigationHelper
        End Get
    End Property
    Private _navigationHelper As Common.NavigationHelper

    ''' <summary>
    ''' This can be changed to a strongly typed view model.
    ''' </summary>
    Public ReadOnly Property DefaultViewModel As Common.ObservableDictionary
        Get
            Return Me._defaultViewModel
        End Get
    End Property
    Private _defaultViewModel As New Common.ObservableDictionary()

    Public Sub New()

        InitializeComponent()
        Me._navigationHelper = New Common.NavigationHelper(Me)
        AddHandler Me._navigationHelper.LoadState, AddressOf NavigationHelper_LoadState
        AddHandler Me._navigationHelper.SaveState, AddressOf NavigationHelper_SaveState
    End Sub

    ''' <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="sender">
    ''' The source of the event; typically <see cref="NavigationHelper"/>
    ''' </param>
    ''' <param name="e">Event data that provides both the navigation parameter passed to
    ''' <see cref="Frame.Navigate"/> when this page was initially requested and
    ''' a dictionary of state preserved by this page during an earlier
    ''' session.  The state will be null the first time a page is visited.</param>
    Private Async Sub NavigationHelper_LoadState(sender As Object, e As Common.LoadStateEventArgs)
        If e.PageState IsNot Nothing AndAlso e.PageState.ContainsKey("mruToken") Then
            Dim value As Object = Nothing
            If e.PageState.TryGetValue("mruToken", value) Then

                If (value IsNot Nothing) Then
                    mruToken = value.ToString()

                    ' Open the file via the token that you stored when adding this file into the MRU list.
                    Dim file =
                        Await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruToken)

                    If (file IsNot Nothing) Then
                        ' Open a stream for the selected file.
                        Dim fileStream = Await file.OpenAsync(Windows.Storage.FileAccessMode.Read)

                        ' Set the image source to a bitmap.
                        Dim BitmapImage = New Windows.UI.Xaml.Media.Imaging.BitmapImage()

                        BitmapImage.SetSource(fileStream)
                        displayImage.Source = BitmapImage

                        ' Set the data context for the page.
                        Me.DataContext = file
                    End If
                End If
            End If
        End If
    End Sub

    ''' <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="Common.SuspensionManager.SessionState"/>.
    ''' </summary>
    ''' <param name="sender">
    ''' The source of the event; typically <see cref="NavigationHelper"/>
    ''' </param>
    ''' <param name="e">Event data that provides a dictionary of state preserved by this page 
    ''' during an earlier session.  The state will be null the first time a page is visited.</param>
    Private Sub NavigationHelper_SaveState(sender As Object, e As Common.SaveStateEventArgs)
        If Not String.IsNullOrEmpty(mruToken) Then
            e.PageState("mruToken") = mruToken
        End If

    End Sub

#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="Common.NavigationHelper.LoadState"/>
    ''' and <see cref="Common.NavigationHelper.SaveState"/>.
    ''' The navigation parameter is available in the LoadState method 
    ''' in addition to page state preserved during an earlier session.

    Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
        _navigationHelper.OnNavigatedTo(e)
    End Sub

    Protected Overrides Sub OnNavigatedFrom(e As NavigationEventArgs)
        _navigationHelper.OnNavigatedFrom(e)
    End Sub

#End Region

    Private Sub PhotoPage_SizeChanged(sender As Object, e As SizeChangedEventArgs) Handles pageRoot.SizeChanged
        If e.NewSize.Height / e.NewSize.Width >= 1 Then
            VisualStateManager.GoToState(Me, "PortraitLayout", True)
        Else
            VisualStateManager.GoToState(Me, "DefaultLayout", True)
        End If
    End Sub

    Private Async Sub GetPhotoButton_Click(sender As Object, e As RoutedEventArgs)

        Dim openPicker = New Windows.Storage.Pickers.FileOpenPicker()
        openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary
        openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail

        ' Filter to include a sample subset of file types.
        openPicker.FileTypeFilter.Clear()
        openPicker.FileTypeFilter.Add(".bmp")
        openPicker.FileTypeFilter.Add(".png")
        openPicker.FileTypeFilter.Add(".jpeg")
        openPicker.FileTypeFilter.Add(".jpg")

        ' Open the file picker.
        Dim file = Await openPicker.PickSingleFileAsync()

        ' file is null if user cancels the file picker.
        If file IsNot Nothing Then

            ' Open a stream for the selected file.
            Dim fileStream = Await file.OpenAsync(Windows.Storage.FileAccessMode.Read)

            ' Set the image source to the selected bitmap.
            Dim BitmapImage = New Windows.UI.Xaml.Media.Imaging.BitmapImage()

            BitmapImage.SetSource(fileStream)
            displayImage.Source = BitmapImage
            Me.DataContext = file

            ' Add picked file to MostRecentlyUsedList.
            mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file)
        End If
    End Sub
End Class

 

 

Show:
© 2014 Microsoft