天天看點

背水一戰 Windows 10 (94) - 選取器: 自定義檔案打開選取器

背水一戰 Windows 10 之 選取器: 自定義檔案打開選取器

[源碼下載下傳]

背水一戰 Windows 10 (94) - 選取器: 自定義檔案打開選取器

作者:webabcd

介紹

背水一戰 Windows 10 之 選取器

  • 自定義檔案打開選取器

示例

1、示範如何開發自定義檔案打開選取器

App.xaml.cs

// 通過檔案打開選取器激活應用程式時所調用的方法
        protected override void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args)
        {
            var rootFrame = new Frame();
            rootFrame.Navigate(typeof(Windows10.Picker.MyOpenPicker), args);
            Window.Current.Content = rootFrame;

            Window.Current.Activate();
        }      

Picker/MyOpenPicker.xaml

<Page
    x:Class="Windows10.Picker.MyOpenPicker"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Picker"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">

            <TextBlock Name="lblMsg" Margin="5" />

            <Button Name="btnPickLocalFile" Content="選擇一個本地檔案" Click="btnPickLocalFile_Click" Margin="5" />

            <Button Name="btnPickRemoteFile" Content="選擇一個遠端檔案" Click="btnPickRemoteFile_Click" Margin="5" />

        </StackPanel>
    </Grid>
</Page>      

Picker/MyOpenPicker.xaml.cs

/*
 * 示範如何開發自定義檔案打開選取器
 * 
 * 1、在 Package.appxmanifest 中新增一個“檔案打開選取器”聲明,并做相關配置
 * 2、在 App.xaml.cs 中 override void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args),如果 app 是由檔案打開選取器激活的,則會調用此方法
 * 
 * FileOpenPickerActivatedEventArgs - 通過“檔案打開選取器”激活應用程式時的事件參數
 *     FileOpenPickerUI - 擷取 FileOpenPickerUI 對象
 *     Kind - 此 app 被激活的類型(ActivationKind 枚舉)
 *         比如,如果是通過“檔案打開選取器”激活的話,則此值為 FileOpenPicker
 *     PreviousExecutionState - 此 app 被激活前的狀态(ApplicationExecutionState 枚舉)
 *         比如,如果此 app 被激活前就是運作狀态的或,則此值為 Running
 *     SplashScreen - 擷取此 app 的 SplashScreen 對象
 *     CallerPackageFamilyName - 擷取激活了此 app 的應用的包名(但是實際測試發現,擷取到的卻是此 app 的包名)
 *     User - 擷取激活了此 app 的 User 對象
 *     
 * FileOpenPickerUI - 自定義檔案打開選取器的幫助類
 *     AllowedFileTypes - 允許的檔案類型,隻讀
 *     SelectionMode - 選擇模式(FileSelectionMode.Single 或 FileSelectionMode.Multiple)
 *     Title - 将在“自定義檔案打開選取器”上顯示的标題
 *     CanAddFile(IStorageFile file) - 是否可以将指定的檔案添加進選中檔案清單
 *     AddFile(string id, IStorageFile file) - 将檔案添加進選中檔案清單,并指定 id
 *     ContainsFile(string id) - 選中檔案清單中是否包含指定的 id
 *     RemoveFile(string id) - 根據 id 從選中檔案清單中删除對應的檔案
 *     Closing - 使用者關閉“自定義檔案打開選取器”時觸發的事件
 *     
 *     
 * 注意:測試時發現如果此 app 作為檔案打開選取器激活之前是運作狀态的話,則在作為檔案打開選取器時會出現控件事件無法觸發的情況(但是有的時候是正常的),不知道為什麼,這一點開發和測試時要注意
 */

using System;
using System.Collections.Generic;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.Storage.Pickers.Provider;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Windows10.Picker
{
    public sealed partial class MyOpenPicker : Page
    {
        private FileOpenPickerUI _fileOpenPickerUI;

        public MyOpenPicker()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 擷取 FileOpenPickerUI 對象(從 App.xaml.cs 傳來的)
            FileOpenPickerActivatedEventArgs args = (FileOpenPickerActivatedEventArgs)e.Parameter;
            _fileOpenPickerUI = args.FileOpenPickerUI;

            _fileOpenPickerUI.Title = "自定義檔案打開選取器";

            // 注意:選擇的檔案的擴充名必須比對 AllowedFileTypes 中的定義(其是在調用端的 FileOpenPicker.FileTypeFilter 中配置的)
            IReadOnlyList<string> allowedFileTypes = _fileOpenPickerUI.AllowedFileTypes;
            lblMsg.Text = "allowedFileTypes: " + string.Join(",", allowedFileTypes);
            lblMsg.Text += Environment.NewLine;

            lblMsg.Text += "Kind: " + args.Kind;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "SplashScreen.ImageLocation: " + args.SplashScreen.ImageLocation;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "PreviousExecutionState: " + args.PreviousExecutionState;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "CallerPackageFamilyName: " + args.CallerPackageFamilyName;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "User.NonRoamableId: " + args.User.NonRoamableId;
            lblMsg.Text += Environment.NewLine;

            // _fileOpenPickerUI.Closing += _fileOpenPickerUI_Closing;

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // _fileOpenPickerUI.Closing -= _fileOpenPickerUI_Closing;

            base.OnNavigatedFrom(e);
        }

        // 選擇一個本地檔案
        private async void btnPickLocalFile_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"Assets\hololens.jpg");
            if (_fileOpenPickerUI.CanAddFile(file))
            {
                AddFileResult result = _fileOpenPickerUI.AddFile("myFile", file);

                lblMsg.Text = "選擇的檔案: " + file.Name;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "AddFileResult: " + result.ToString();
            }
        }

        // 選擇一個遠端檔案
        private async void btnPickRemoteFile_Click(object sender, RoutedEventArgs e)
        {
            Uri uri = new Uri("http://images.cnblogs.com/mvpteam.gif", UriKind.Absolute);

            // 擴充名必須比對 FileOpenPicker.FileTypeFilter 中的定義
            StorageFile file = await StorageFile.CreateStreamedFileFromUriAsync("mvp.gif", uri, RandomAccessStreamReference.CreateFromUri(uri));
            if (_fileOpenPickerUI.CanAddFile(file))
            {
                AddFileResult result = _fileOpenPickerUI.AddFile("myFile", file);

                lblMsg.Text = "選擇的檔案: " + file.Name;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += "AddFileResult: " + result.ToString();
            }
        }
    }
}      

2、示範如何調用自定義檔案打開選取器

Picker/MyOpenPickerDemo.xaml

<Page
    x:Class="Windows10.Picker.MyOpenPickerDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.Picker"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="10 0 10 10">

            <TextBlock Name="lblMsg" TextWrapping="Wrap" Margin="5">
                <Run>
                    如果需要激活自定義的檔案選取視窗,請在彈出的選取器視窗的左側的導航清單中選擇相應的 app
                </Run>
                <LineBreak />
                <Run>
                    測試時發現如果此 app 作為檔案打開選取器激活之前是運作狀态的話,則在作為檔案打開選取器時會出現控件事件無法觸發的情況(但是有的時候是正常的),不知道為什麼,這一點開發和測試時要注意
                </Run>
            </TextBlock>

            <Button Name="btnMyOpenPicker" Content="彈出檔案選擇視窗" Click="btnMyOpenPicker_Click" Margin="5" />

        </StackPanel>
    </Grid>
</Page>      

Picker/MyOpenPickerDemo.xaml.cs

/*
 * 示範如何調用自定義檔案打開選取器
 * 
 * 自定義檔案打開選取器參見 MyOpenPicker.xaml
 */

using System;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Windows10.Picker
{
    public sealed partial class MyOpenPickerDemo : Page
    {
        public MyOpenPickerDemo()
        {
            this.InitializeComponent();
        }

        private async void btnMyOpenPicker_Click(object sender, RoutedEventArgs e)
        {
            // 選擇一個檔案
            FileOpenPicker openPicker = new FileOpenPicker();
            openPicker.CommitButtonText = "選中此檔案";
            openPicker.FileTypeFilter.Add("*");

            // 彈出檔案選擇視窗
            StorageFile file = await openPicker.PickSingleFileAsync(); 
            if (file != null)
            {
                lblMsg.Text = "選中檔案: " + file.Name;
            }
            else
            {
                lblMsg.Text = "取消了";
            }
        }
    }
}      

OK