文件访问和选取器
步驟 1:使用文件選取器獲取圖像文件
通過文件選取器,你的應用可以在用戶的整個系統(tǒng)上訪問文件和文件夾。當你調用文件選取器時,用戶可以瀏覽其系統(tǒng)并選擇文件(或文件夾)以訪問和保存。在用戶選取文件或文件夾之后,你的應用將這些選取作為?StorageFile?和StorageFolder?對象進行接收。接著你的應用可以通過使用這些對象在選取的文件和文件夾上操作。
你需要做的第一件事就是處理?GetPhotoButton_Click?事件以獲取要顯示的圖片。
我們先從部分 3:導航、布局和視圖中的代碼開始。
添加文件選取器
以下是選擇圖片的應用的外觀。
讓我們來仔細查看使用?FileOpenPicker?的代碼。若要使用文件選取器,你需要執(zhí)行 3 個基本步驟:確保文件選取器可以打開,創(chuàng)建并自定義文件選取器對象以及顯示文件選取器以使用戶可以選取一個項。
你無法在輔視圖中打開文件選取器。因此,在調用文件選取器之前,必須首先確保應用未貼靠,如果貼靠,則必須調用TryUnsnap?方法來取消貼靠。
C# VB if (Windows.UI.ViewManagement.ApplicationView.Value != Windows.UI.ViewManagement.ApplicationViewState.Snapped ||Windows.UI.ViewManagement.ApplicationView.TryUnsnap() == true)接下來,創(chuàng)建?FileOpenPicker?對象。
C# VB Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker();在文件選取器對象上設置與你的用戶和你的應用相關的屬性。有關幫助你確定如何自定義文件選取器的指南,請參閱文件選取器指南。
由于用戶正在選取圖片,因此會將?SuggestedStartLocation?設置為圖片庫,將?ViewMode?設置為?Thumbnail。還會添加文件類型篩選器,以便選取器僅顯示為圖像文件指定的文件類型。
C# VB 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");在你創(chuàng)建和自定義文件選取器后,調用?FileOpenPicker.PickSingleFileAsync?以顯示該選取器并讓用戶選取一個文件。
注意??若要讓用戶選取多個文件,請調用?PickMultipleFilesAsync。
C# VB // Open the file picker. Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();用戶選取文件時,PickSingleFileAsync?返回表示已選取文件的?StorageFile?對象。處理圖像流以創(chuàng)建?BitmapImage?并將?BitmapImage?設置為 UI 中?Image?控件的?Source。還將文件設置為頁面的?DataContext,以便可以將 UI 元素綁定到其屬性。
C# VB // file is null if user cancels the file picker. if (file != null) {// Open a stream for the selected fileWindows.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; }步驟 2:將 UI 控件綁定到文件數(shù)據(jù)
此時,圖像會顯示在 UI 中,但圖像文件屬性不會顯示在添加的文本塊中。可以在代碼中設置每個?TextBlock?的?Text?屬性,就像設置?Image.Source?屬性一樣。
但對于顯示數(shù)據(jù),通常會使用“數(shù)據(jù)綁定”將數(shù)據(jù)源連接到 UI,方法是設置?Binding.Source?屬性或在 UI 元素上設置DataContext。建立綁定后,如果數(shù)據(jù)源發(fā)生更改,綁定到該數(shù)據(jù)源的 UI 元素可以自動反映更改內容。
注意??默認情況下,綁定為?one-way,這表示數(shù)據(jù)源的更新會在 UI 中反映出來。你可以指定?two-way?綁定,以便用戶在 UI 元素中所做的更改可以在數(shù)據(jù)源中反映出來。例如,如果用戶編輯了?TextBox?中的值,則綁定引擎將自動更新基礎數(shù)據(jù)源以反映該變化。
使用?DataContext?屬性可設置整個 UI 元素的默認綁定,包括其所有子元素。將在?FileOpenPicker?中選擇的StorageFile?設置為照片頁面的?DataContext。請注意,在選取圖像后,將使用此代碼行設置?DataContext。
C# VB this.DataContext = file;此時,通過將標題?TextBlock?的?Text?屬性綁定到所選文件的?StorageFile.DisplayName?屬性來顯示文件名。
由于不指定綁定的?Source,因此數(shù)據(jù)綁定引擎會在?DataContext?上查找?DisplayName?屬性。如果?DataContext?為null?或沒有?DisplayName?屬性,則綁定會失敗并且不會給出任何提示,且?TextBlock?中不會顯示任何文本。
此時,將?TextBlock?控件綁定到?StorageFile?屬性。
將控件綁定到數(shù)據(jù)
注意??“屬性標記”是每個屬性值右側的小框符號。Text?屬性標記為黑色,表示該屬性已設置為字符串值。
注意??“創(chuàng)建數(shù)據(jù)綁定”對話框中的消息表明數(shù)據(jù)上下文尚未設置。這是可以的,因為在運行應用和獲取圖片時會在代碼中設置數(shù)據(jù)上下文。
下面是添加綁定后?TextBlock?的可擴展應用程序標記語言 (XAML)。
XAML <TextBlock Grid.Row="1" TextWrapping="Wrap" Text="{Binding DisplayName}" Style="{StaticResource PageSubheaderTextStyle}"/>下面是添加綁定后照片信息?StackPanel?的 XAML。
XAML <StackPanel Margin="20,0,0,0"><TextBlock Text="File name:" Style="{StaticResource CaptionTextStyle}"/><TextBlock Text="{Binding Name}" Style="{StaticResource ItemTextStyle}" Margin="10,0,0,30"/><TextBlock Text="Path:" Style="{StaticResource CaptionTextStyle}"/><TextBlock Text="{Binding Path}" Style="{StaticResource ItemTextStyle}" Margin="10,0,0,30"/><TextBlock Text="Date created:" Style="{StaticResource CaptionTextStyle}"/><TextBlock Text="{Binding DateCreated}" Style="{StaticResource ItemTextStyle}" Margin="10,0,0,30"/></StackPanel>以下是當選擇圖片和將文本塊綁定到數(shù)據(jù)時應用的外觀。
步驟 3:保存和加載狀態(tài)
在此教程系列的部分 2:管理應用生命周期和狀態(tài)中,你已了解到如何保存和還原應用狀態(tài)。在將新頁面添加到應用后,還需要保存和加載新頁面的狀態(tài)。有關照片頁面,只需保存和還原當前顯示的圖像文件。
但是無法僅將路徑保存到文件,然后使用該路徑重新打開該文件。當用戶選取具有?FileOpenPicker?的文件時,他們會隱式授予應用該文件的權限。如果你嘗試以后僅使用該路徑檢索文件,則拒絕使用該權限。
相反,若要保留該文件的訪問權限以便將來使用,則?StorageApplicationPermissions?類提供了 2 個列表,你可以在其中存儲文件及其權限,當用戶使用文件選取器打開該文件時會授予這些權限。
- MostRecentlyUsedList?- 用于存儲最后訪問的 25 個文件。
- FutureAccessList?- 用于常規(guī)存儲,最多 1000 個文件,以便將來訪問。
當用戶選取文件后,會將其添加到?MostRecentlyUsedList。我們將文件添加到此列表后,MostRecentlyUsedList?會返回你用于以后檢索文件的令牌。將此令牌保存在?pageState?字典中,并使用該令牌在還原頁面狀態(tài)時檢索當前圖像文件。
保存狀態(tài)
以下是該代碼及其周圍代碼。
C# VB public sealed partial class PhotoPage : HelloWorld.Common.LayoutAwarePage {private string mruToken = null;public PhotoPage(){this.InitializeComponent();} ...以下是該代碼及其周圍代碼。
C# VB // 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.mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file); }以下是?SaveState?方法的完整代碼。
C# VB protected override void SaveState(Dictionary<String, Object> pageState) {if (!String.IsNullOrEmpty(mruToken)){pageState["mruToken"] = mruToken;} }加載狀態(tài)
此時,從?pageState?字典中獲取令牌。使用該令牌從?MostRecentlyUsedList?中檢索文件并還原 UI 狀態(tài)。
C# VB 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;}}}}注意??查看部分 2:管理應用生命周期和狀態(tài)獲取有關如何掛起、終止以及還原應用的說明。
總結
- 上一篇: 三种基础的布局控件
- 下一篇: 页面导航的基础与深入