zoukankan      html  css  js  c++  java
  • 33、ShareSource

         分享功能在 Win8 平台是一个很重要的内容,这个功能简化了系统间应用的分享操作。记得在 windows  phone 上如果要进行

    内容的分享,比如分享到 新浪微博、腾讯微博、人人等,都需要在自己的应用中引入它们的 SDK,同时增加了学习、调试的成本。

    而在 win8 平台上,只要按照分享的契约,任何应用都可以似乎分享源、任何应用也都可以接收分享。本示例演示分享源,34、演示分享

    目标。

       分享操作:点击右侧面板超级按钮中的“共享”按钮(快捷键 win键 + H),或者以编程的方式调用。

    本篇文章中将要使用的  Windows.ApplicationModel.DataTransfer 中的类:

    namespace Windows.ApplicationModel.DataTransfer
    {
        
        // 通过其他应用程序以编程方式启动内容的交换。
        public sealed class DataTransferManager
        {
            
           // 在共享操作开始时发生。
            public event TypedEventHandler<DataTransferManager, DataRequestedEventArgs> DataRequested;
           
           // 当用户在共享魅力中选择选择目标时发生。
            public event TypedEventHandler<DataTransferManager, TargetApplicationChosenEventArgs> TargetApplicationChosen;
    
          
           // 返回与当前窗口关联的 DataTransferManager 对象。    
            // 返回结果: 与当前窗口关联的 DataTransferManager 对象。
            public static DataTransferManager GetForCurrentView();
    
           // 摘要: 使用其他应用程序以编程方式启动用于共享内容的用户界面。
            public static void ShowShareUI();
        }
    }
    namespace Windows.ApplicationModel.DataTransfer
    {
       
        // 包含 DataRequested 事件的相关信息。当调用共享 UI 时,系统会激发此事件。
        public sealed class DataRequestedEventArgs
        {
              // 让您可以获取 DataRequest 对象,并为其提供数据或失败消息。
            // 返回结果: 用于管理作为共享操作一部分的内容的对象。
            public DataRequest Request { get; }
        }
    }
    namespace Windows.ApplicationModel.DataTransfer
    {
     
        //如果发生错误,允许您的应用程序提供用户希望共享或指定消息的内容。
        public sealed class DataRequest
        {
           //设置或获取包含用户想要共享内容的 DataPackage 对象。
            // 返回结果: 包含用户希望共享的内容。
            public DataPackage Data { get; set; }
           
           // 获取完成延迟的呈现操作的截止日期。如果执行超出该截止日期范围,则将忽略延迟的呈现的结果。
            // 返回结果: 延迟的呈现操作的截至日期。
            public DateTimeOffset Deadline { get; }
          
           // 取消共享操作并提供错误字符串以显示给用户。     
            // value:  要显示给用户的文本。
            public void FailWithDisplayText(string value);
           
           // 通过创建并返回 DataRequestDeferral 对象支持异步共享操作。       
            // 返回结果: 可让您异步共享或发送内容的对象。
            public DataRequestDeferral GetDeferral();
        }
    }
    namespace Windows.ApplicationModel.DataTransfer
    {
       
        //包含用户希望与另一个应用程序交换的数据。
        public sealed class DataPackage
        {
           
           //创建新 DataPackage 的构造函数。
            public DataPackage();
    
           
           // 可让您获取和设置属性,如共享内容的标题。       
            // 返回结果:  描述 DataPackage. 中包含的数据的属性集合
            public DataPackagePropertySet Properties { get; }
          
           //  指定该操作的 DataPackageOperation(无,移动、复制或链接)。
            // 返回结果: 源应用程序的操作请求。
            public DataPackageOperation RequestedOperation { get; set; }
           
           // 将 URI 映射到文件。用于确保 HTML 内容中的引用内容(如图像)添加到 DataPackage。
            // 返回结果:  指定名称/值对,该对指定具有对应的 StreamReference 的 HTML 路径。
            public IDictionary<string, RandomAccessStreamReference> ResourceMap { get; }
    
            
           // 在销毁 DataPackage 时发生。
            public event TypedEventHandler<DataPackage, object> Destroyed;
           
           //在粘贴操作完成时发生。
            public event TypedEventHandler<DataPackage, OperationCompletedEventArgs> OperationCompleted;
    
    
           // 返回 DataPackageView 对象。这是 DataPackage 对象的只读副本的对象。      
            // 返回结果: 是 DataPackage 对象的只读副本的对象。
            public DataPackageView GetView();
         
            // 设置 DataPackage 中包含的位图图像。
             // value:  包含位图图像的流。
             public void SetBitmap(RandomAccessStreamReference value);
           
           //设置 RandomAccessStream 格式的 DataPackage 中包含的数据。      
            // formatId: 指定数据的格式。建议使用 StandardDataFormats 类设置此值。      
            // value:  指定 DataPackage 包含的内容。
            public void SetData(string formatId, object value);
           
           //设置委托以处理来自目标应用程序的请求。      
            // formatId: 指定数据的格式。建议使用 StandardDataFormats 类设置此值。      
            // delayRenderer: 负责处理来自目标应用程序的请求的委托。
            public void SetDataProvider(string formatId, DataProviderHandler delayRenderer);
          
           //向 DataPackage 添加 HTML 内容。    
            // value: HTML 内容。
            public void SetHtmlFormat(string value);
           
            // 设置 DataPackage 中包含 RTF 格式内容。
             // value:  指定 DataPackage RTF 内容。
             public void SetRtf(string value);
          
            public void SetStorageItems(IEnumerable<global::Windows.Storage.IStorageItem> value);
           
            public void SetStorageItems(IEnumerable<global::Windows.Storage.IStorageItem> value, bool readOnly);
           
            //设置 DataPackage 包含的文本。
             // value:   文本。
             public void SetText(string value);
            public void SetUri(Uri value);
        }
    }

        首先,定义一个间接继承自 Page 类的 SharePage 类,使具有分享功能的页面都继承这个 SharePage 类:

    namespace SDKTemplate.Common
    {
        public abstract class SharePage : SDKTemplate.Common.LayoutAwarePage
        {
    
           public const string MissingTitleError = "Enter a title for what you are sharing and try again.";
    
            //通过其他应用程序以编程方式启动内容的交换。
             private DataTransferManager dataTransferManager;
    
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
                //把当前页面注册为一个分享源
                 this.dataTransferManager = DataTransferManager.GetForCurrentView();
                this.dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>
    (this.OnDataRequested); } protected override void OnNavigatedFrom(NavigationEventArgs e) { // 取消注册当前页面为一个分享源 this.dataTransferManager.DataRequested -= new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>
    (this.OnDataRequested); } // 当分享功能被调用时(用户手动调用 或者 点击右侧的分享超级按钮), //下面已经注册的方法将被调用,从而进行初始化 DataPackage 对象的操作 private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e) { // 调用 SharePage 的子类中,重写的 GetShareContent() 方法,进而组合 datapackage 对象 if (GetShareContent(e.Request)) { // 在 datapackage 对象中,title 字段是必须的 if (String.IsNullOrEmpty(e.Request.Data.Properties.Title)) { //取消共享操作并提供错误字符串以显示给用户。 e.Request.FailWithDisplayText(MissingTitleError); } } } protected void ShowUIButton_Click(object sender, RoutedEventArgs e) { // 如果用户单击分享按钮,以编程的方式调用分享功能。 DataTransferManager.ShowShareUI(); } // 这个抽象方法用于每个其它示例中去实现共享内容(文本、链接、图像等)。 protected abstract bool GetShareContent(DataRequest request); } }

    1、Share text :

        分享文本:

        页面的 xaml :

     <TextBox x:Name="TitleInputBox"  Text="What are Metro Style Apps?" />
    
     <TextBox x:Name="DescriptionInputBox"  Text="Selected text from the Share Source sample" />
    
     <TextBox x:Name="TextToShare"  TextWrapping="Wrap"  AcceptsReturn="True"  Text="Metro style apps are full screen 
    apps tailored to your users' needs, tailored to the device they run on,
    tailored for touch interaction, and tailored to the Windows user interface.
    Windows helps you interact with your users, and your users interact with your app.
    " />


    分享 按钮:

    //调用 SharePage 中的 ShowUIButton_Click 方法
    <Button x:Name="ShowUIButton" Content="Share"  Click="ShowUIButton_Click" />

    相应页面的 C# :

    protected override bool GetShareContent(DataRequest request)
    {
        bool succeeded = false;
    
        string dataPackageText = TextToShare.Text;
        if (!String.IsNullOrEmpty(dataPackageText))
        {
           //设置或获取包含用户想要共享内容的 DataPackage 对象。
            DataPackage requestData = request.Data;
    
           // 获取或设置显示为 DataPackage 的内容的标题的文本。
            requestData.Properties.Title = TitleInputBox.Text;
    
           // 获取或设置描述 DataPackage 的内容的文本。
            requestData.Properties.Description = DescriptionInputBox.Text; // 描述是可选的
    
           //设置 DataPackage 包含的文本。
            requestData.SetText(dataPackageText);
           succeeded = true;
        }
        else
        {
    
           //取消共享操作并提供错误字符串以显示给用户。
            request.FailWithDisplayText("Enter the text you would like to share and try again.");
        }
        return succeeded;
    }


    操作截图:

    将要分享的文本 :

    点击 "Share" 按钮,即可选择能够“接收文本分享”的应用:

    2、Share link :

         基本和 1、类似,代码将简述。

         页面的 xaml :

    //将要分享的文本和链接
    
    <TextBox x:Name="TitleInputBox" Text="Building Windows 8" />
    
     <TextBox x:Name="DescriptionInputBox" Text="An inside look from the Windows engineering team" />
    
    <TextBox x:Name="UriToShare"   Text="http://blogs.msdn.com/b/b8/" />
    <Button x:Name="ShowUIButton" Content="Share"  Click="ShowUIButton_Click"  />

    相应的 C# :

    protected override bool GetShareContent(DataRequest request)
    {
        bool succeeded = false;
    
        // 验证 URI 的合法性
       Uri dataPackageUri = ValidateAndGetUri(UriToShare.Text);
        if (dataPackageUri != null)
        {
            DataPackage requestData = request.Data;
            requestData.Properties.Title = TitleInputBox.Text;
            requestData.Properties.Description = DescriptionInputBox.Text; // 描述是可选的
            requestData.SetUri(dataPackageUri);
            succeeded = true;
        }
        else
        {
            request.FailWithDisplayText("Enter the link you would like to share and try again.");
        }
        return succeeded;
    }
    
    private Uri ValidateAndGetUri(string uriString)
    {
        Uri uri = null;
        try
        {
            uri = new Uri(uriString);
        }
        catch (FormatException)
        {
           //URI    不合法
        }
        return uri;
    }


    操作截图 :

    点击 “Share” 按钮,注意到这次和 1、中的不同,可以接收 URI 的应用增加了:

    3、Share image :

        分享图片 :

        页面的 xaml :

    <TextBox x:Name="TitleInputBox"  Text="My image" />
    
     <TextBox x:Name="DescriptionInputBox" Text="Selected image from the Share Source sample" />
    
    //显示选择的图片文件
     <Image x:Name="ImageHolder" AutomationProperties.Name="A placeholder image" />
    
    //从电脑中选择图片
    <Button Content="Select image"  Click="SelectImageButton_Click" />

    对应的 C# :

    首先声明一个全局的文件变量 :

    private StorageFile imageFile;
    //从本地选择一张图片
    private async void SelectImageButton_Click(object sender, RoutedEventArgs e)
    {
            FileOpenPicker imagePicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                FileTypeFilter = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
            };
    
            StorageFile pickedImage = await imagePicker.PickSingleFileAsync();
    
            if (pickedImage != null)
            {
                this.imageFile = pickedImage;
    
                //在文件中打开一个随机访问流
                IRandomAccessStream displayStream = await pickedImage.OpenAsync(FileAccessMode.Read);
    
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(displayStream);
                ImageHolder.Source = bitmapImage;
                
            }
        
    }
    //分享图片
     protected override bool GetShareContent(DataRequest request)
     {
         bool succeeded = false;
    
         if (this.imageFile != null)
         {
             DataPackage requestData = request.Data;
             requestData.Properties.Title = TitleInputBox.Text;
             requestData.Properties.Description = DescriptionInputBox.Text; // 描述是可选的
    
             //推荐使用两 SetBitmap 和 SetStorageItems 共享单个图像
            //因为目标应用程序可能只支持一个或其他。
            // IStorageItem : 操作存储项(文件和文件夹)及其内容,并提供有关它们的信息。
             List<IStorageItem> imageItems = new List<IStorageItem>();
            imageItems.Add(this.imageFile);
            requestData.SetStorageItems(imageItems);
    
            //在文件附近创建随机访问流。
             RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(this.imageFile);
             
            //Thumbnail : 获取或设置 DataPackage 的缩略图像。
             requestData.Properties.Thumbnail = imageStreamRef;
    
            //设置 DataPackage 中包含的位图图像。
             requestData.SetBitmap(imageStreamRef);
            succeeded = true;
         }
         else
         {
             request.FailWithDisplayText("Select an image you would like to share and try again.");
         }
         return succeeded;
     }

    操作截图:

    点击“Select image” 按钮 :

    点击 “Share” 按钮 :

    4、Share files :

         分享文件 :

          页面的 xaml :

    //将要分享的文本
     <TextBox x:Name="TitleInputBox"  Text="My files" />
    
     <TextBox x:Name="DescriptionInputBox"  Text="Selected files from the Share Source sample" />
    
    //选择一个文件
    <Button  Content="Select files" Click="SelectFilesButton_Click" />
    
    //分享操作
    <Button x:Name="ShowUIButton" Content="Share"  Click="ShowUIButton_Click" />

    相应的 C#  :

    定义一个全局的变量,用来存放选择的文件的集合:

     private IReadOnlyList<StorageFile> storageItems;

    选择文件:

     private async void SelectFilesButton_Click(object sender, RoutedEventArgs e)
     {
            FileOpenPicker filePicker = new FileOpenPicker
             {
    
               // 获取或设置文件打开选择器用于显示项目的视图模式 :  项的列表。
                 ViewMode = PickerViewMode.List,
               SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
               
    //
    获取文件打开选择器显示的文档类型的集合。 FileTypeFilter = { "*" } }; //显示文件选取器,以便用户可以选择多个文件。 IReadOnlyList<StorageFile> pickedFiles = await filePicker.PickMultipleFilesAsync(); if (pickedFiles.Count > 0) { this.storageItems = pickedFiles; string selectedFiles = String.Empty; for (int index = 0; index < pickedFiles.Count; index++) { selectedFiles += pickedFiles[index].Name; if (index != (pickedFiles.Count - 1)) { selectedFiles += ", "; } } //告诉用户选择的文件的集合的名称 : selectedFiles }
    }


    分享操作:

    protected override bool GetShareContent(DataRequest request)
    {
        bool succeeded = false;
    
        if (storageItems != null)
        {
            DataPackage requestData = request.Data;
            requestData.Properties.Title = TitleInputBox.Text;
            requestData.Properties.Description = DescriptionInputBox.Text; // 描述是可选的
            requestData.SetStorageItems(this.storageItems);
            succeeded = true;
        }
        else
        {
            request.FailWithDisplayText("Select the files you would like to share and try again.");
        }
        return succeeded;
    }


    操作截图:

    点击 “Select files” 按钮,显示选择的文件 :

    点击 “Share” 按钮, 显示可以接收 .txt 文件的应用 :

    5、Share delay rendered files :

         有时你可能希望为共享提供的内容为不同的格式或大小。然而,你可能不想立即准备将要分享的内容,直到目标应用真正需要它时才准备。在这种情况下,你应该使用延迟渲染。

        为了演示,请为共享的选择一个图像。当目标应用程序请求数据时,图像将会被源程序进行缩放。因为图像处理可能需要一些时间,图像处理将延迟,直到到它的请求的目标应用程序发出请求。

    页面的 xaml  :

    // 选择一个文件
    <Button x:Name="SelectImageButton" Content="Select image" Click="SelectImageButton_Click" />
    
     <Button Content="Share"  Click="ShowUIButton_Click" />
    
    //显示选择的文件
     <Image x:Name="ImageHolder" AutomationProperties.Name="A placeholder image" />

    相应的 C# :

    定义一个全局的文件变量 :

     private StorageFile selectedImage;

    选择文件按钮 :

    private async void SelectImageButton_Click(object sender, RoutedEventArgs e)
    {
           FileOpenPicker imagePicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                FileTypeFilter = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
            };
    
            StorageFile pickedImage = await imagePicker.PickSingleFileAsync();
    
            if (pickedImage != null)
            {
                this.selectedImage = pickedImage;
    
                // 把图片显示在页面上
                 IRandomAccessStream displayStream = await pickedImage.OpenAsync(FileAccessMode.Read);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(displayStream);
                ImageHolder.Source = bitmapImage;
              
                // 告诉用户选择的文件的集合的名称 : pickedImage.Name 
            }
        }
    }


    分享操作 :

            protected override bool GetShareContent(DataRequest request)
            {
                bool succeeded = false;
    
                if (this.selectedImage != null)
                {
                    DataPackage requestData = request.Data;
                    requestData.Properties.Title = "Delay rendered image";
                    requestData.Properties.Description = "Resized image from the Share Source sample";
                    requestData.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(this.selectedImage);
    
                    //设置委托以处理来自目标应用程序的请求。
                    //StandardDataFormats.Bitmap : 返回与位图格式相对应的格式 ID 字符串值的只读属性。
                      requestData.SetDataProvider(StandardDataFormats.Bitmap, providerRequest 
    => this.OnDeferredImageRequestedHandler(providerRequest, this.selectedImage)); succeeded = true; } else { request.FailWithDisplayText("Select an image you would like to share and try again."); } return succeeded; }
     private async void OnDeferredImageRequestedHandler(DataProviderRequest providerRequest, StorageFile imageFile)
     {
         // 在这个委托里我们使用延迟渲染提供更新的位图数据。
    
         if (imageFile != null)
         {
             // If the delegate is calling any asynchronous operations it needs to acquire the deferral first. This lets the
             // system know that you are performing some operations that might take a little longer and that the call to
             // SetData could happen after the delegate returns. Once you acquired the deferral object you must call Complete
             // on it after your final call to SetData.
            // 通过延迟的共享操作返回使用的 DataRequestDeferral。
             DataProviderDeferral deferral = providerRequest.GetDeferral();
    
            //在文件中打开一个随机访问流。
             InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();
    
            // 确保当完成延迟时,总是调用 Complete 方法
             try
             {
                // 解码图像并把它编码为50%的宽度和高度。
                 IRandomAccessStream imageStream = await imageFile.OpenAsync(FileAccessMode.Read);
    
                //异步创建新的 BitmapDecoder 并使用流将其初始化。
                 BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imageStream);
                 
               //异步创建新的 BitmapEncoder 并使用来自现有 BitmapDecoder 的数据将其初始化。
                 BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);
    
                // 指定任何转换缩略图的宽度(以像素为单位)。
                 imageEncoder.BitmapTransform.ScaledWidth = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
    
                // 指定任何转换缩略图的高度(以像素为单位)。
                 imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
    
               //异步提交当前帧数据并刷新图像文件上的所有数据。
                 await imageEncoder.FlushAsync();
    
    
               //CreateFromStream(inMemoryStream) : 在指定的流附近创建随机访问流。返回结果: 封装 stream 的随机访问流。
                 providerRequest.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream));
             }
             finally
             {
                 //通知目标应用程序 DataPackage 已准备好进行处理。
                  deferral.Complete();
             }
         }
     }


    操作截图 :

    点击 “Select image” 按钮,选择图片文件 :

    点击 “Share” 按钮,显示电脑上可以接收此分享的应用:

    6、Share HTML content :

         你可以分享包含 HTML 标签的内容 。

       页面的 xaml :

     
    <ProgressRing x:Name="LoadingProgressRing" IsActive="true" Height="50" Width="50"/>
    
    //显示微软的 MSDN 首页
    <WebView x:Name="ShareWebView" Height="400" Visibility="Collapsed" LoadCompleted="ShareWebView_LoadCompleted" />
    //分享按钮
    <Button Content="Share"  Click="ShowUIButton_Click" />

    相应的 C# :

    在页面的构造函数中添加 :

    //导航 WebView
    ShareWebView.Navigate(new Uri("http://msdn.microsoft.com"));
    //当 WebView 加载网页完成时调用
     private void ShareWebView_LoadCompleted(object sender, NavigationEventArgs e)
     {
         ShareWebView.Visibility = Windows.UI.Xaml.Visibility.Visible;
          LoadingProgressRing.IsActive = false;
     }

    分享按钮 :

    protected override bool GetShareContent(DataRequest request)
    {
        bool succeeded = false;
    
        // 获取传递给 WebView 的剪贴板 DataPackage。返回结果: 剪贴板数据包。
        DataPackage requestData = ShareWebView.DataTransferPackage;
        DataPackageView dataPackageView = requestData.GetView();
    
       //dataPackageView.AvailableForma : 返回 DataPackageView 包含的格式。
        if ((dataPackageView != null) && (dataPackageView.AvailableFormats.Count > 0))
        {
            requestData.Properties.Title = "A web snippet for you";
            requestData.Properties.Description = "HTML selection from a WebView control"; // 描述是可选的
            request.Data = requestData;
            succeeded = true;
        }
        else
        {
            request.FailWithDisplayText("Make a selection in the WebView control and try again.");
        }
        return succeeded;
    }


    页面操作截图 :

    点击  Share 按钮 ,弹出共享面板(暂时没有可以接受 html 内容的应用):

    7、Share custom data :

         用户自定义的数据格式可以被分享到支持它们的应用上。本例讲述的分享数据的格式为 Json。这个格式

     会被分享到 下篇文章中的 Share Target 示例。

    页面中的 xaml :

    //Data Package Title:
    <TextBox x:Name="TitleInputBox"  Text="The Catcher in the Rye" />
    
    //Data Package Description:
    <TextBox x:Name="DescriptionInputBox"  Text="My favorite book" />
    
    //Custom Data Format Id:
     <TextBox x:Name="DataFormatInputBox" Text="http://schema.org/Book" />
    
    //Custom Data Format Value:
    <TextBox x:Name="CustomDataTextBox" />
    
    
    //分享按钮
    <Button x:Name="ShowUIButton" Content="Share"  Click="ShowUIButton_Click" />

    相应的 C# 页面:

    在页面的构造函数中初始化  CustomDataTextBox.Text :

    CustomDataTextBox.Text =
    @"{
       ""type"" : ""http://schema.org/Book"",
       ""properties"" :
       {
        ""image"" : ""http://sourceurl.com/catcher-in-the-rye-book-cover.jpg"",
        ""name"" : ""The Catcher in the Rye"",
        ""bookFormat"" : ""http://schema.org/Paperback"",
        ""author"" : ""http://sourceurl.com/author/jd_salinger.html"",
        ""numberOfPages"" : 224,
        ""publisher"" : ""Little, Brown, and Company"",
        ""datePublished"" : ""1991-05-01"",
        ""inLanguage"" : ""English"",
        ""isbn"" : ""0316769487""
        }
    }";

    分享按钮 :

    protected override bool GetShareContent(DataRequest request)
    {
        bool succeeded = false;
    
        string dataPackageFormat = DataFormatInputBox.Text;
        if (!String.IsNullOrEmpty(dataPackageFormat))
        {
            string dataPackageText = CustomDataTextBox.Text;
            if (!String.IsNullOrEmpty(dataPackageText))
            {
                DataPackage requestData = request.Data;
                requestData.Properties.Title = TitleInputBox.Text;
                requestData.Properties.Description = DescriptionInputBox.Text; //描述是可选的
    
                 //SetData(string formatId, object value) :
               // 设置 RandomAccessStream 格式的 DataPackage 中包含的数据。
                // formatId: 指定数据的格式。建议使用 StandardDataFormats 类设置此值。
                //value: 指定 DataPackage 包含的内容。
                requestData.SetData(dataPackageFormat, dataPackageText);
              ucceeded = true;
            }
            else
            {
                request.FailWithDisplayText("Enter the custom data you would like to share and try again.");
            }
        }
        else
        {
            request.FailWithDisplayText("Enter a custom data format and try again.");
        }
        return succeeded;
    }

    8、Fail with display text :

         当用户尝试分享你应用中的内容,但是你的应用不支持一些内容的分享时,你可以提供显示在分享窗口中的错误信息提示页面。

     这些信息可以让用户理解为什么这些不能被分享,然后怎样处理这些问题从而完成操作。如果你的应用本身就不支持分享操作,

    比不比使用这个方法,因为 windows 系统已经提供了一个默认的提示。

    页面的 xaml :

    //显示提示给用户的提示
    <TextBox x:Name="CustomErrorText"  Text="You have selected too many images. Select fewer than 50 images and then try again." />

    点击超级按钮上面的“共享”按钮(或者 win键 + H):

    protected override bool GetShareContent(DataRequest request)
    {
        string errorMessage = CustomErrorText.Text;
        if (String.IsNullOrEmpty(errorMessage))
        {
            errorMessage = "Enter a failure display text and try again.";
        }
     
         //取消共享操作并提供错误字符串以显示给用户。
        request.FailWithDisplayText(errorMessage);
        return false;
    }


    操作截图:

    点击超级按钮面板上面的 “共享”按钮:

  • 相关阅读:
    UVA10361
    △UVA10494
    △UVA465
    △UVA10106
    △UVA424
    阶乘的精确值
    小学生算术
    UVA156
    △UVA120
    linux应用之ntpdate命令联网同步时间
  • 原文地址:https://www.cnblogs.com/hebeiDGL/p/2715648.html
Copyright © 2011-2022 走看看