日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

文件访问和选取器

發布時間:2025/6/15 编程问答 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 文件访问和选取器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

步驟 1:使用文件選取器獲取圖像文件

通過文件選取器,你的應用可以在用戶的整個系統上訪問文件和文件夾。當你調用文件選取器時,用戶可以瀏覽其系統并選擇文件(或文件夾)以訪問和保存。在用戶選取文件或文件夾之后,你的應用將這些選取作為?StorageFile?和StorageFolder?對象進行接收。接著你的應用可以通過使用這些對象在選取的文件和文件夾上操作。

你需要做的第一件事就是處理?GetPhotoButton_Click?事件以獲取要顯示的圖片。

我們先從部分 3:導航、布局和視圖中的代碼開始。

添加文件選取器

  • 在“解決方案資源管理器”中,雙擊 PhotoPage.xaml 打開它。
  • 選擇“獲取照片”""?Button
  • 在“屬性”窗口中,單擊“事件”按鈕 ()。
  • 在事件列表的頂部查找?Click?事件。在事件的文本框中,鍵入 "GetPhotoButton_Click" 作為處理?Click?事件的方法的名稱。
  • 按 Enter。事件處理程序方法在代碼編輯器中創建和打開,因此你可以添加在事件出現時執行的代碼。
  • 將?async?關鍵字添加到事件處理程序的方法簽名中。 C# VB private async void GetPhotoButton_Click(object sender, RoutedEventArgs e) { }
  • 將此代碼添加到事件處理程序方法中。該方法會打開文件選取器,讓用戶從圖片庫中選擇一張圖片。 當他們選取某個文件時,該文件會設置為圖像源和頁面的數據上下文。 C# VB // 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;// mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file);}}
  • 按 F5 構建并運行應用。導航到照片頁面,然后單擊""“獲取照片”按鈕啟動?FileOpenPicker。隨即會出現照片,但照片信息文本還未更新。將在下一步中修復該問題。

    以下是選擇圖片的應用的外觀。

  • 讓我們來仔細查看使用?FileOpenPicker?的代碼。若要使用文件選取器,你需要執行 3 個基本步驟:確保文件選取器可以打開,創建并自定義文件選取器對象以及顯示文件選取器以使用戶可以選取一個項。

    你無法在輔視圖中打開文件選取器。因此,在調用文件選取器之前,必須首先確保應用未貼靠,如果貼靠,則必須調用TryUnsnap?方法來取消貼靠。

    C# VB if (Windows.UI.ViewManagement.ApplicationView.Value != Windows.UI.ViewManagement.ApplicationViewState.Snapped ||Windows.UI.ViewManagement.ApplicationView.TryUnsnap() == true)

    接下來,創建?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");

    在你創建和自定義文件選取器后,調用?FileOpenPicker.PickSingleFileAsync?以顯示該選取器并讓用戶選取一個文件。

    注意??若要讓用戶選取多個文件,請調用?PickMultipleFilesAsync

    C# VB // Open the file picker. Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();

    用戶選取文件時,PickSingleFileAsync?返回表示已選取文件的?StorageFile?對象。處理圖像流以創建?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 控件綁定到文件數據

    此時,圖像會顯示在 UI 中,但圖像文件屬性不會顯示在添加的文本塊中。可以在代碼中設置每個?TextBlock?的?Text?屬性,就像設置?Image.Source?屬性一樣。

    但對于顯示數據,通常會使用“數據綁定”將數據源連接到 UI,方法是設置?Binding.Source?屬性或在 UI 元素上設置DataContext。建立綁定后,如果數據源發生更改,綁定到該數據源的 UI 元素可以自動反映更改內容。

    注意??默認情況下,綁定為?one-way,這表示數據源的更新會在 UI 中反映出來。你可以指定?two-way?綁定,以便用戶在 UI 元素中所做的更改可以在數據源中反映出來。例如,如果用戶編輯了?TextBox?中的值,則綁定引擎將自動更新基礎數據源以反映該變化。

    使用?DataContext?屬性可設置整個 UI 元素的默認綁定,包括其所有子元素。將在?FileOpenPicker?中選擇的StorageFile?設置為照片頁面的?DataContext。請注意,在選取圖像后,將使用此代碼行設置?DataContext

    C# VB this.DataContext = file;

    此時,通過將標題?TextBlock?的?Text?屬性綁定到所選文件的?StorageFile.DisplayName?屬性來顯示文件名。

    由于不指定綁定的?Source,因此數據綁定引擎會在?DataContext?上查找?DisplayName?屬性。如果?DataContext?為null?或沒有?DisplayName?屬性,則綁定會失敗并且不會給出任何提示,且?TextBlock?中不會顯示任何文本。

    此時,將?TextBlock?控件綁定到?StorageFile?屬性。

    將控件綁定到數據

  • 在“解決方案資源管理器”中,雙擊 PhotoPage.xaml 打開它。
  • 為“獲取照片”""按鈕下的照片名稱選擇?TextBlock
  • 在“屬性”面板中,單擊“屬性”按鈕 ()?以顯示“屬性”視圖。
  • 在“屬性”面板的“常用”下,單擊?Text?屬性的“屬性標記”。此時將打開“屬性”菜單。

    注意??“屬性標記”是每個屬性值右側的小框符號。Text?屬性標記為黑色,表示該屬性已設置為字符串值。

  • 在“屬性”菜單中,選擇“創建數據綁定...”。隨即將打開“創建數據綁定”對話框。
  • 在“創建數據綁定”對話框中,選擇“綁定類型”下拉列表中的“數據上下文”
  • 在此處顯示的“路徑”文本框中輸入 "DisplayName"

    注意??“創建數據綁定”對話框中的消息表明數據上下文尚未設置。這是可以的,因為在運行應用和獲取圖片時會在代碼中設置數據上下文。

  • 單擊“確定”

    下面是添加綁定后?TextBlock?的可擴展應用程序標記語言 (XAML)。

    XAML <TextBlock Grid.Row="1" TextWrapping="Wrap" Text="{Binding DisplayName}" Style="{StaticResource PageSubheaderTextStyle}"/>
  • 選擇“文件名:”""后的?TextBlockTextBlock
  • 重復步驟 3-5 為此?TextBlock?創建數據綁定。
  • 在“路徑”文本框中輸入 "Name" 并單擊“確定”
  • 選擇“路徑:”""后的?TextBlockTextBlock
  • 重復步驟 3-5 為此?TextBlock?創建數據綁定。
  • 在“路徑”文本框中輸入 "Path" 并單擊“確定”
  • 選擇“創建日期:”""后的?TextBlock?TextBlock
  • 重復步驟 3-5 為此?TextBlock?創建數據綁定。
  • 在“路徑”文本框中輸入“DateCreated”""并單擊“確定”
  • 下面是添加綁定后照片信息?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>
  • 按 F5 構建并運行應用。導航到照片頁。單擊“獲取照片”""按鈕可啟動?FileOpenPicker。使用適當的綁定,當選取文件時不會顯示文件屬性。

    以下是當選擇圖片和將文本塊綁定到數據時應用的外觀。

  • 步驟 3:保存和加載狀態

    在此教程系列的部分 2:管理應用生命周期和狀態中,你已了解到如何保存和還原應用狀態。在將新頁面添加到應用后,還需要保存和加載新頁面的狀態。有關照片頁面,只需保存和還原當前顯示的圖像文件。

    但是無法僅將路徑保存到文件,然后使用該路徑重新打開該文件。當用戶選取具有?FileOpenPicker?的文件時,他們會隱式授予應用該文件的權限。如果你嘗試以后僅使用該路徑檢索文件,則拒絕使用該權限。

    相反,若要保留該文件的訪問權限以便將來使用,則?StorageApplicationPermissions?類提供了 2 個列表,你可以在其中存儲文件及其權限,當用戶使用文件選取器打開該文件時會授予這些權限。

    • MostRecentlyUsedList?- 用于存儲最后訪問的 25 個文件。
    • FutureAccessList?- 用于常規存儲,最多 1000 個文件,以便將來訪問。
    僅需要訪問用戶選取的最后一個文件,以便可以使用該文件還原頁面狀態。鑒于此原因, MostRecentlyUsedList ?符合你的需要。

    當用戶選取文件后,會將其添加到?MostRecentlyUsedList。我們將文件添加到此列表后,MostRecentlyUsedList?會返回你用于以后檢索文件的令牌。將此令牌保存在?pageState?字典中,并使用該令牌在還原頁面狀態時檢索當前圖像文件。

    保存狀態

  • 在“解決方案資源管理器”中,雙擊 PhotoPage.xaml.cs/vb 打開它。
  • 在?PhotoPage?類的頂部,添加此代碼。該代碼會聲明一個變量來保存?MostRecentlyUsedList?返回的令牌。 C# VB private string mruToken = null;

    以下是該代碼及其周圍代碼。

    C# VB public sealed partial class PhotoPage : HelloWorld.Common.LayoutAwarePage {private string mruToken = null;public PhotoPage(){this.InitializeComponent();} ...
  • 在?GetPhotoButton_Click?事件處理程序中,添加此代碼。該代碼將選取的文件添加到?MostRecentlyUsedList?并獲取令牌。 C# VB // Add picked file to MostRecentlyUsedList. mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file);

    以下是該代碼及其周圍代碼。

    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?方法中,添加此代碼。該代碼會檢查令牌是否存在,如果存在,則將其保存在?pageState?字典中。 C# VB if (!String.IsNullOrEmpty(mruToken)){pageState["mruToken"] = mruToken;}

    以下是?SaveState?方法的完整代碼。

    C# VB protected override void SaveState(Dictionary<String, Object> pageState) {if (!String.IsNullOrEmpty(mruToken)){pageState["mruToken"] = mruToken;} }
  • 加載狀態

  • 在 PhotoPage.xaml.cs/vb 中,向?LoadState?方法簽名添加?async?關鍵字。 C# VB protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { }
  • 在?LoadState?方法中添加此代碼。

    此時,從?pageState?字典中獲取令牌。使用該令牌從?MostRecentlyUsedList?中檢索文件并還原 UI 狀態。

    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;}}}}
  • 按 F5 構建并運行應用。導航至照片頁面,然后單擊“獲取照片”""按鈕以啟動?FileOpenPicker?并選取文件。當應用掛起、終止以及還原時,會立即重新加載圖像。

    注意??查看部分 2:管理應用生命周期和狀態獲取有關如何掛起、終止以及還原應用的說明。

  • 總結

    以上是生活随笔為你收集整理的文件访问和选取器的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。