Xaml选择要保存文件的类型
前台代码:
<Canvas Background="{StaticResource AppBarBackgroundThemeBrush}">
<TextBox Name="txtContent" Width="1365" Height="696" TextWrapping="Wrap" FontSize="18" Canvas.Top="1"/>
<Button Content="保存到文件" Canvas.Left="710" FontSize="15" Canvas.Top="702" Padding="25,17" Click="btnSave_Click" RenderTransformOrigin="-0.844,0.395" Height="60"/>
<TextBlock Name="Msg" FontSize="20" Canvas.Left="1015" Canvas.Top="722" RenderTransformOrigin="-1.207,0.583" /> <TextBox TextWrapping="Wrap" Text="支持多格保存文件,您可以写日记、Word、Txt等等...方便的用户的写作,快来体验吧" Canvas.Top="712" Width="574" Canvas.Left="10" Height="46"/>
</Canvas>
</Page>
后台代码:
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;
// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍
namespace 选择保存文件 { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private async void btnSave_Click(object sender, RoutedEventArgs e) { if (this.txtContent.Text.Equals(string.Empty)) { return; } FileSavePicker picker = new FileSavePicker(); // 提交按钮上显示的文本 picker.CommitButtonText = "保存"; // 支持的文件类型 picker.FileTypeChoices.Add("文本文件", new string[] { ".txt" }); picker.FileTypeChoices.Add("Word文档", new string[] { ".doc" }); picker.FileTypeChoices.Add("写字板", new string[] { ".rtf " }); picker.FileTypeChoices.Add("文档模板", new string[] { ".dot " }); picker.FileTypeChoices.Add("WPS", new string[] { ".wps " }); picker.FileTypeChoices.Add("Word平台", new string[] { ".wpt " }); picker.FileTypeChoices.Add("网页", new string[] { ".html " }); picker.FileTypeChoices.Add("数据", new string[] { ".data " }); picker.FileTypeChoices.Add("数据库", new string[] { ".dbf " }); picker.FileTypeChoices.Add("日记本", new string[] { ".jnt " }); picker.FileTypeChoices.Add("可扩展标识语言", new string[] { ".xml" });
// 默认显示的目录 picker.SuggestedStartLocation = PickerLocationId.Desktop; // 显示UI并返回内容 StorageFile file = await picker.PickSaveFileAsync(); // 向文件写入内容 if (file != null) { await FileIO.WriteTextAsync(file, txtContent.Text, Windows.Storage.Streams.UnicodeEncoding.Utf8); this.Msg.Text = "文件已保存。"; } } } }