图解使用Win8Api进行Metro风格的程序开发二----使用文件选择器访问和保存文件
我們緊接著上篇,這篇將介紹如何使用文件選擇器訪問和保存文件
-----------------------------------我是華麗的分割線-----------------------------------------
此示例演示用戶如何使用文件選擇器選擇您的應用程序文件和文件夾,
根據用戶指定的名稱,文件類型和文件保存的位置。
這個示例使用Windows.Storage.Pickers API。
本篇將介紹如下四個方面:
a)讓用戶選擇一個文件
b)讓用戶選擇多個文件
c)讓用戶選擇一個文件夾
d)讓用戶保存文件和指定的名稱,文件類型和/或保存位置
我們的創建的步驟如下:
1)為了組織文件方便,我們先建一個文件夾FilePicker
2)向文件夾中添加如下四個文件:
PickAFolder.xaml,PickASinglePhoto.xaml,PickMultipleFiles.xaml,SaveAFile.xaml
創建方式如圖:
3)此時的解決方案結構如下:
4)向我們的DataSource添加導航所需要的信息
修改我們的SampleDataSource.cs文件中的SampleDataSource類中的代碼,
代碼如下:
View Code public sealed class SampleDataSource{private static SampleDataSource _sampleDataSource = new SampleDataSource();private ObservableCollection<SampleDataGroup> _allGroups = new ObservableCollection<SampleDataGroup>();public ObservableCollection<SampleDataGroup> AllGroups{get { return this._allGroups; }}public static IEnumerable<SampleDataGroup> GetGroups(string uniqueId){if (!uniqueId.Equals("AllGroups")) throw new ArgumentException("Only 'AllGroups' is supported as a collection of groups");return _sampleDataSource.AllGroups;}public static SampleDataGroup GetGroup(string uniqueId){// Simple linear search is acceptable for small data setsvar matches = _sampleDataSource.AllGroups.Where((group) => group.UniqueId.Equals(uniqueId));if (matches.Count() == 1) return matches.First();return null;}public static SampleDataItem GetItem(string uniqueId){// Simple linear search is acceptable for small data setsvar matches = _sampleDataSource.AllGroups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));if (matches.Count() == 1) return matches.First();return null;}public SampleDataSource(){var group1 = new SampleDataGroup("FilePicker","Use Windows.Storage.Pickers API","Access and save files using the file picker","Assets/FilePicker.jpg","");group1.Items.Add(new SampleDataItem("FilePicker-PickASinglePhoto","Pick a single photo","only one file can selected,file type is jpg,jpeg,png","Assets/FilePicker.jpg","only one file can selected ","",group1,typeof(PickASinglePhoto)));group1.Items.Add(new SampleDataItem("FilePicker-PickMultipleFiles","Pick multiple files","you can pick multiple files","Assets/FilePicker.jpg","pick multiple files","",group1,typeof(PickMultipleFiles)));group1.Items.Add(new SampleDataItem("FilePicker-PickAFolder","Pick a folder","you can pick a folder","Assets/FilePicker.jpg","Pick a folder","",group1,typeof(PickAFolder)));group1.Items.Add(new SampleDataItem("FilePicker-SaveAFile","Save a file","you can save a file","Assets/FilePicker.jpg","Save a file","",group1,typeof(SaveAFile)));this.AllGroups.Add(group1);}}?
5)我們的導航這樣就做好了,效果圖:
點擊,出現如下圖片:
6)我們開始我們的任務:讓用戶選擇一個文件
使用的FileOpenPicker的PickSingleFileAsync方法來調用一個文件選擇器窗口,
讓用戶選擇一個單一的文件。
修改PickASinglePhoto.xaml的代碼:
View Code <Grid x:Name="LayoutRoot" Background="{StaticResource ApplicationPageBackgroundThemeBrush}" HorizontalAlignment="Left" VerticalAlignment="Top"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><Grid x:Name="Input" Grid.Row="0"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><TextBlock Grid.Row="0" TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >Prompt the user to pick a single photo.</TextBlock><Button Grid.Row="1" x:Name="PickAFileButton" Content="Pick photo" Margin="0,10,10,0"/></Grid><Grid x:Name="Output" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top"><TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" /></Grid></Grid>?
修改后臺代碼:
View Code public sealed partial class PickASinglePhoto : Page{public PickASinglePhoto(){this.InitializeComponent();PickAFileButton.Click += new RoutedEventHandler(PickAFileButton_Click);}/// <summary>/// Invoked when this page is about to be displayed in a Frame./// </summary>/// <param name="e">Event data that describes how this page was reached. The Parameter/// property is typically used to configure the page.</param>protected override void OnNavigatedTo(NavigationEventArgs e){}private async void PickAFileButton_Click(object sender, RoutedEventArgs e){FileOpenPicker openPicker = new FileOpenPicker();//設置呈現視圖模式為縮略圖openPicker.ViewMode = PickerViewMode.Thumbnail;//設置文件選擇器打開時的起始位置,這里設置為圖片庫openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;//添加文件過濾器openPicker.FileTypeFilter.Add(".jpg");openPicker.FileTypeFilter.Add(".jpeg");openPicker.FileTypeFilter.Add(".png");//異步調用PickSingleFileAsyncStorageFile file = await openPicker.PickSingleFileAsync();if (file != null){OutputTextBlock.Text = "Picked photo: " + file.Name;}else{OutputTextBlock.Text = "Operation cancelled.";}}}?
效果圖如下:
7)讓用戶選擇多個文件
使用的FileOpenPicker的PickMultipleFilesAsync方法來調用一個文件選擇器窗口,
讓用戶選擇多個文件。
修改我們的PickMultipleFiles.xaml
代碼如下:
View Code <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><Grid x:Name="Input" Grid.Row="0"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><TextBlock Grid.Row="0" TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >Prompt the user to pick one or more files.</TextBlock><Button Grid.Row="1" x:Name="PickFilesButton" Content="Pick files" Margin="0,10,10,0"/></Grid><Grid x:Name="Output" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top"><TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" /></Grid></Grid>后臺代碼:
View Code public sealed partial class PickMultipleFiles : Page{public PickMultipleFiles(){this.InitializeComponent();PickFilesButton.Click += new RoutedEventHandler(PickFilesButton_Click);}/// <summary>/// Invoked when this page is about to be displayed in a Frame./// </summary>/// <param name="e">Event data that describes how this page was reached. The Parameter/// property is typically used to configure the page.</param>protected override void OnNavigatedTo(NavigationEventArgs e){}private async void PickFilesButton_Click(object sender, RoutedEventArgs e){FileOpenPicker openPicker = new FileOpenPicker();//設置呈現視圖模式為列表openPicker.ViewMode = PickerViewMode.List;//設置文件選擇器打開時的起始位置,這里設置為文檔庫openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;//不過濾任何類型openPicker.FileTypeFilter.Add("*");//調用PickMultipleFilesAsync獲得選擇文件列表IReadOnlyList<StorageFile> files = await openPicker.PickMultipleFilesAsync();if (files.Count > 0){StringBuilder output = new StringBuilder("Picked files:\n");foreach (StorageFile file in files){output.Append(file.Name + "\n");}OutputTextBlock.Text = output.ToString();}else{OutputTextBlock.Text = "Operation cancelled.";}} }?
效果圖:
8)讓用戶選擇一個文件夾
使用的FolderPicker的PickSingleFolderAsync方法來調用一個文件選擇器窗口,
讓用戶選擇一個文件夾。
修改我們的PickAFolder.xaml的xmal代碼:
View Code <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><Grid x:Name="Input" Grid.Row="0"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><TextBlock Grid.Row="0" TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >Prompt the user to pick a folder so its contents can be accessed later.</TextBlock><Button Grid.Row="1" x:Name="PickFolderButton" Content="Pick folder" Margin="0,10,10,0"/></Grid><Grid x:Name="Output" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top"><TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" /></Grid></Grid>?
修改后臺代碼:
View Code public sealed partial class PickAFolder : Page{public PickAFolder(){this.InitializeComponent();PickFolderButton.Click += new RoutedEventHandler(PickFolderButton_Click);}/// <summary>/// Invoked when this page is about to be displayed in a Frame./// </summary>/// <param name="e">Event data that describes how this page was reached. The Parameter/// property is typically used to configure the page.</param>protected override void OnNavigatedTo(NavigationEventArgs e){}private async void PickFolderButton_Click(object sender, RoutedEventArgs e){FolderPicker folderPicker = new FolderPicker();folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;folderPicker.FileTypeFilter.Add(".jpg");//調用PickSingleFolderAsync選擇文件夾StorageFolder folder = await folderPicker.PickSingleFolderAsync();if (folder != null){// 提供對列表的訪問,使用該列表,應用程序可以跟蹤最近訪問的文件或位置和將來要存儲的文件或位置StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);OutputTextBlock.Text = "Picked folder: " + folder.Name;}else{OutputTextBlock.Text = "Operation cancelled.";}}}?
效果圖:
9)讓用戶保存文件和指定的名稱,文件類型和/或保存位置
使用的FileSavePicker的PickSaveFileAsync方法來調用一個文件選擇器窗口,
讓用戶保存文件。
修改我們的SaveAFile.xaml的代碼:
View Code <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><Grid x:Name="Input" Grid.Row="0"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><TextBlock Grid.Row="0" TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left" >Prompt the user to save a file.</TextBlock><Button Grid.Row="1" x:Name="SaveFileButton" Content="Save file" Margin="0,10,10,0"/></Grid><Grid x:Name="Output" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top"><TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap" /></Grid></Grid>?
修改后臺代碼:
View Code public sealed partial class SaveAFile : Page{public SaveAFile(){this.InitializeComponent();SaveFileButton.Click += new RoutedEventHandler(SaveFileButton_Click);}/// <summary>/// Invoked when this page is about to be displayed in a Frame./// </summary>/// <param name="e">Event data that describes how this page was reached. The Parameter/// property is typically used to configure the page.</param>protected override void OnNavigatedTo(NavigationEventArgs e){}private async void SaveFileButton_Click(object sender, RoutedEventArgs e){FileSavePicker savePicker = new FileSavePicker();savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;// 指定要保存的類型savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });// 默認的文件名savePicker.SuggestedFileName = "Refactor's blog";//調用保存文件方法StorageFile file = await savePicker.PickSaveFileAsync();if (file != null){// 阻止更新,直到我們完成更新文件,我們完成更新后調用CompleteUpdatesAsync方法 CachedFileManager.DeferUpdates(file);// 寫文件 await FileIO.WriteTextAsync(file, file.Name);// 讓系統知道我們正在完成更新文件,以便其他程序可以更新該文件FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);if (status == FileUpdateStatus.Complete){OutputTextBlock.Text = "File " + file.Name + " was saved.";}else{OutputTextBlock.Text = "File " + file.Name + " couldn't be saved.";}}else{OutputTextBlock.Text = "Operation cancelled.";}}}?
效果圖就不發了!你懂的,圖太多了....
?
未完待續,敬請期待...
轉載請注明出處:http://www.cnblogs.com/refactor/
總結
以上是生活随笔為你收集整理的图解使用Win8Api进行Metro风格的程序开发二----使用文件选择器访问和保存文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VMware Workstation 8
- 下一篇: USACO1.4 The Clocks(