This topic provides the complete code sample used in the tutorial Part 4: File access and pickers.
This topic contains these sections:
Download location
This sample is not available for download.
Technologies
| Programming languages | C#, Visual Basic .NET |
|---|---|
| Programming models | Windows Runtime |
Requirements
| Minimum supported client | Windows 8 |
|---|---|
| Minimum supported server | Windows Server 2012 |
| Minimum required SDK | Microsoft Visual Studio Express 2012 for Windows 8 |
View the code ()
App.xaml
App.xaml is unchanged from Part 3.
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
<common:LayoutAwarePage 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"> <Page.Resources> <!-- 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 Style="{StaticResource LayoutRootStyle}"> <Grid.RowDefinitions> <RowDefinition Height="140"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!-- Back button and page title --> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/> <TextBlock x:Name="pageTitle" Grid.Column="1" Text="{StaticResource AppName}" Style="{StaticResource PageHeaderTextStyle}"/> </Grid> <Grid 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="{StaticResource PageSubheaderTextStyle}"/> <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="{StaticResource CaptionTextStyle}"/> <TextBlock TextWrapping="Wrap" Text="{Binding Name}" Style="{StaticResource ItemTextStyle}" Margin="10,0,0,30"/> <TextBlock TextWrapping="Wrap" Text="Path:" Style="{StaticResource CaptionTextStyle}"/> <TextBlock TextWrapping="Wrap" Text="{Binding Path}" Style="{StaticResource ItemTextStyle}" Margin="10,0,0,30"/> <TextBlock TextWrapping="Wrap" Text="Date created:" Style="{StaticResource CaptionTextStyle}"/> <TextBlock TextWrapping="Wrap" Text="{Binding Path}" Style="{StaticResource ItemTextStyle}" Margin="10,0,0,30"/> </StackPanel> </StackPanel> </Grid> <VisualStateManager.VisualStateGroups> <!-- Visual states reflect the application's view state --> <VisualStateGroup x:Name="ApplicationViewStates"> <VisualState x:Name="FullScreenLandscape"/> <VisualState x:Name="Filled"/> <!-- The entire page respects the narrower 100-pixel margin convention for portrait --> <VisualState x:Name="FullScreenPortrait"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PortraitBackButtonStyle}"/> </ObjectAnimationUsingKeyFrames> <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> <!-- The back button and title have different styles when snapped --> <VisualState x:Name="Snapped"> <Storyboard> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton" Storyboard.TargetProperty="Style"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedBackButtonStyle}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetName="pageTitle" Storyboard.TargetProperty="Style"> <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedPageHeaderTextStyle}"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Margin)" Storyboard.TargetName="contentGrid"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Thickness>20,0,0,20</Thickness> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(StackPanel.Orientation)" Storyboard.TargetName="imagePanel"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Orientation>Vertical</Orientation> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </common:LayoutAwarePage>
PhotoPage.xaml.cs/vb
using System; using System.Collections.Generic; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237 namespace HelloWorld { /// <summary> /// A basic page that provides characteristics common to most applications. /// </summary> public sealed partial class PhotoPage : HelloWorld.Common.LayoutAwarePage { private string mruToken = null; public PhotoPage() { this.InitializeComponent(); } /// <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> protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { if (pageState != null && pageState.ContainsKey("mruToken")) { object value = null; if (pageState.TryGetValue("mruToken", out value)) { if (value != null) { mruToken = value.ToString(); // Open the file via the token that you stored when adding this file into the MRU list. Windows.Storage.StorageFile file = await Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(mruToken); if (file != null) { // Open a stream for the selected file. Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); // Set the image source to a bitmap. Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bitmapImage.SetSource(fileStream); displayImage.Source = bitmapImage; // Set the data context for the page. this.DataContext = file; } } } } } /// <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> protected override void SaveState(Dictionary<String, Object> pageState) { if (!String.IsNullOrEmpty(mruToken)) { pageState["mruToken"] = mruToken; } } private async void GetPhotoButton_Click(object sender, RoutedEventArgs e) { // File picker APIs don't work if the app is in a snapped state. // If the app is snapped, try to unsnap it first. Only show the picker if it unsnaps. if (Windows.UI.ViewManagement.ApplicationView.Value != Windows.UI.ViewManagement.ApplicationViewState.Snapped || Windows.UI.ViewManagement.ApplicationView.TryUnsnap() == true) { Windows.Storage.Pickers.FileOpenPicker 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. Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync(); // file is null if user cancels the file picker. if (file != null) { // Open a stream for the selected file. Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); // Set the image source to the selected bitmap. Windows.UI.Xaml.Media.Imaging.BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); bitmapImage.SetSource(fileStream); displayImage.Source = bitmapImage; this.DataContext = file; // Add picked file to MostRecentlyUsedList and get a token. mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file); } } } } }
Build date: 3/11/2013