老周的博客http://blog.csdn.net/tcjiaan,转载请注明原作者和出处。
在WinForm时代,我们不能忘记OpenFileDialog,那么,在windows store应用中,又有什么组件功能与之相似呢?
它就是Windows.Storage.Pickers.FileOpenPicker,其实,从类的名字我们同样可以知道它的用途,看来,学会几个单词是很必要的哦。
FileOpenPicker可以选择单个文件(单选)或多个文件(多选),选择文件提交后,它会返回一个Windows.Storage.StorageFile,这个类你可以认为它就表示一个文件,后面我们会认识它,现在先卖个关子。
那么,具体怎么操作呢?其实,学习一个新东西,世界上没有比实例更直观的东西了。
现在,跟着我的步骤,你也来试试吧。(用什么语言你喜欢,我用CS)
1、启动VS for Win8,新建一个空白页面的App。
2、在主页MainPage.xaml中,放一个按钮button,和一个Image
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
<Button Margin="6,1,3,5" Content="请选择一个文件" Click="onSelectFile"/>
<TextBlock Name="displayPath" Margin="12,1,0,5" FontSize="18"/>
</StackPanel>
<Image Grid.Row="1" Name="img" Stretch="Uniform" Margin="15"/>
</Grid>
3、打开代码文件MainPage.xaml.cs,其中代码如下。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
namespace OpenFilePickerSample
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void onSelectFile(object sender, RoutedEventArgs e)
{
FileOpenPicker picker = new FileOpenPicker(); //实例化一个FileOpenPicker
// 添加文件类型过滤,如.jpg,.txt等
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
// 设置初始路径
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
// PickMultipleFilesAsync是选取多个文件,
// PickSingleFileAsync选取单个文件
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.displayPath.Text = file.Path;
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
// 新建一个位图
Windows.UI.Xaml.Media.Imaging.BitmapImage bmp = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
bmp.SetSource(stream);
// 显示图片
this.img.Source = bmp;
}
}
}
}
SuggestedStartLocation属性表示,当我们启用文件选择器时显示哪个目录下的内容,它是一个枚举值。
要选取单个文件,应调用PickSingleFileAsync,若要选取多个文件,就调用PickMultipleFilesAsync方法,这两个方法都是异步执行的,因此,需要添加await关键字。
按F5运行应用程序,点击“请选择一个文件”按钮,然后随便选一张图片,确定,返回,页面上就显示我们刚才选的图片。