Maui 教學 – 現在就介紹四個常用的Maui功能, 分別為:
- File Picker
- Secure Storage
- Clipboard
- Screenshot.
Let’s copy and paste.
File Picker |
private async void Button_Clicked(object sender, EventArgs e) { //打開FILE PICKER版面選FILE var result = await PickAndShow(); if (result != null) { //取DATA if (result.FileName.EndsWith(“txt”, StringComparison.OrdinalIgnoreCase)) { var txt = new StreamReader(await result.OpenReadAsync()).ReadToEnd(); editorView.Text = txt; } } } public async Task<FileResult> PickAndShow() { try { var customFileType = new FilePickerFileType( new Dictionary<DevicePlatform, IEnumerable<string>> { { DevicePlatform.iOS, new[] { “public.my.text.extension” } }, { DevicePlatform.Android, new[] { “application/text” } }, { DevicePlatform.WinUI, new[] { “.txt” } }, { DevicePlatform.Tizen, new[] { “*/*” } }, { DevicePlatform.macOS, new[] { ” txt ” } }, }); PickOptions options = new() { PickerTitle = “Please select a comic file”, FileTypes = customFileType, }; var result = await FilePicker.Default.PickAsync(options); return result; } catch (Exception ex) { //被USER CANCEL或出了BUG } return null; } |
Secure Storage |
把STRING 放入SecureStorage, 這可以為一般的STRING, JSON STRING等. await SecureStorage.Default.SetAsync(“password”, “12345678”); 把RESULT從SecureStorage拿出來 string password = await SecureStorage.Default.GetAsync(“password”); |
Clipboard |
把TEXT放進Clipboard內 await Clipboard.Default.SetTextAsync(“Hello World!”); 從Clipboard內拿出TEXT if (Clipboard.Default.HasText) { ClipboardOutputLabel.Text = await Clipboard.Default.GetTextAsync(); await Clipboard.Default.SetTextAsync(null); } |
Screenshot |
if (Screenshot.Default.IsCaptureSupported) { //Capture Screen IScreenshotResult screen = await Screenshot.Default.CaptureAsync(); //存儲至Local Storage string localFilePath = Path.Combine(FileSystem.CacheDirectory, “CaptureScreen.jpg”); Stream sourceStream = await screen.OpenReadAsync(); FileStream localFileStream = File.OpenWrite(localFilePath); sourceStream.CopyTo(localFileStream); localFileStream.Flush(); localFileStream.Close(); localFileStream.Dispose(); return localFilePath; } |