Windows 8 Store Apps Learning (39) Contract: Share Contract

Source: Internet
Author: User
Tags count xmlns

Introduced

Re-imagine the contract for Windows 8 Store Apps

Share Contract-Right sidebar called Charm, where "sharing" is called Share Contract

Example

1. Demonstrates how to develop a shared source

Contracts/sharecontract/sharesource.xaml

<page x:class= "XamlDemo.Contracts.ShareContract.ShareSource" xmlns= "http://schemas.microsoft.com/winfx/2006/x Aml/presentation "xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "xmlns:local=" using: XamlDemo.Contracts.ShareContract "xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "xmlns:mc=" http:// schemas.openxmlformats.org/markup-compatibility/2006 "mc:ignorable=" D "> <grid background=" Transparent "&
        Gt
    
            <stackpanel margin= "0 0 0" > <textblock name= "lblmsg" fontsize= "14.667"/> <button content= "Share Text" click= "button_click_1" margin= "0 0 0"/> <button content= "Shar E Link "click=" button_click_1 "margin=" 0 0 0 "/> <button content=" Share Image "click=" button_cli Ck_1 "margin=" 0 0 0 "/> <button content=" Share File "click=" button_click_1 "margin=" 0 10 0 0 "/&
    
            Gt <button Content= "Share Html" click= "button_click_1" margin= "0 0 0"/> <button "content= Custom Data" Cli ck= "Button_click_1" margin= "0 0 0"/> <button content= "Share with Deferral" click= "Button_click_ 1 "margin=" 0 0 0 "/> </StackPanel> </Grid> </Page>

Contracts/sharecontract/sharesource.xaml.cs

* * Share Contract-The right-hand sidebar is called the Charm, where "sharing" is called Share Contract * * * This example demonstrates how to develop a shared source * Shared Source-the app that provides shared data share target-receive and process shared numbers According to the app * Sharing panel-click "Share" comes out, contains a bunch of shared target panels * * Datatransfermanager-shared Data Manager * Getforcurrentview ()-Returns the current window associated Datat Ransfermanager Object * Showshareui ()-pops up the shared panel to start the shared operation * datarequested-Events triggered by the start of the shared operation (that is, after the shared panel), and the event parameters are DataTransfer Manager and Datarequestedeventargs * Targetapplicationchosen-events that are triggered when a shared target on the shared panel is selected, and the event parameters are Datatransfermanager and Targe  Tapplicationchoseneventargs * Targetapplicationchoseneventargs-targetapplicationchosen Event parameters * ApplicationName -The name of the selected shared target * * datarequestedeventargs-datarequested event parameter * Request-returns data of type Datarequest * Dat Arequest-An object that includes shared content and error hints * FAILWITHDISPLAYTEXT ()-Specifies the message to be displayed on the shared panel when a shared operation fails-the content that needs to be shared, returned Datapack         Age Object * * datapackage-shared content (note: Content copied to the Clipboard is also encapsulated through this object) * Properties-Return Datapackagepropertysetview Object * Properties.title- Title of Shared data * properties.description-Description of shared data * properties.thumbnail-thumbnail of shared data * Properties.file Types-Gets the file types contained in the shared data * SetText (), Seturi (), Sethtmlformat (), Setrtf (), SetBitmap (), Setstorageitems (), SetData (), S Etdataprovider ()-Set up data in various formats that need to be shared, detailed usage see the relevant demo below (note: A datapackage can have many different formats of data) * RESOURCEMAP-IDICTIONARY&LT;STR ING, randomaccessstreamreference> type, when sharing HTML if it contains a reference to a local resource (such as referencing a local picture), you need to pass Resourcemap * GetView ()-Return Datap Ackageview object, which is equivalent to a read-only copy of Datapackage, see ShareTarget.xaml.cs * Another: Webview.datatransferpackage returns the user-selected content Datapack The age object to share the HTML content in the browser * Asynchronous sharing: * 1, Datapackage pass the data through Setdataprovider (), its corresponding delegate parameter is a dataproviderrequest type number According to * 2, dataproviderrequest.getdeferral () is used to get the Dataproviderdeferral object to start the asynchronous processing, and then through Dataproviderdeferral.complete () notification
Datapackage has completed the asynchronous operation * * using System;
Using System.Collections.Generic;
Using System.Threading.Tasks; Using WINDOWS.APPLICATIONMODEL.DATATRANSFER
Using Windows.storage;
Using Windows.Storage.Pickers;
Using Windows.Storage.Streams;
Using Windows.UI.ViewManagement;
Using Windows.UI.Xaml;
Using Windows.UI.Xaml.Controls;
Using Windows.UI.Xaml.Navigation;
Using System.Linq;
    
Using Windows.Graphics.Imaging; Namespace XamlDemo.Contracts.ShareContract {public sealed partial class Sharesource:page {//current content to be shared
        The type private string _sharetype = "Share Text";
    
        Need to share the collection of files private ireadonlylist<storagefile> _selectedfiles; Public Sharesource () {this.
        InitializeComponent (); } protected override void Onnavigatedto (NavigationEventArgs e) {//Initialize Datatransfermanag
            Er datatransfermanager datatransfermanager = Datatransfermanager.getforcurrentview ();
            datatransfermanager.datarequested + = datatransfermanager_datarequested; Datatransfermanager.targetapplicationchosen + + DatatransfermanagEr_targetapplicationchosen;
            } void Datatransfermanager_datarequested (Datatransfermanager sender, Datarequestedeventargs args) { When a shared operation starts (that is, after the shared panel is ejected), executes the specified method switch (_sharetype) {case "Sh" based on the type of content that needs to be shared.
                    Are Text ": Sharetext (sender, args);
                Break
                    Case "Share Link": Sharelink (sender, args);
                Break
                    Case "Share Image": Shareimage (sender, args);
                Break
                    Case "Share File": Sharefile (sender, args);
                Break
                    Case "Share with deferral": sharewithdeferral (sender, args);
                Break
                    Case "Share Html": sharehtml (sender, args);
                Break Case "Share Custom Data": Sharecustomdata (SendeR, args);
                Break
            Default:break; ////args the message displayed on the shared panel when the shared operation fails. 
        Request.failwithdisplaytext ("Shared operation failed"); } void Datatransfermanager_targetapplicationchosen (Datatransfermanager sender, Targetapplicationchoseneventar GS args) {//display the name of the application to which the user needs to share content Lblmsg.text = "shared to:" + args.
        ApplicationName; Private async void Button_click_1 (object sender, RoutedEventArgs e) {_sharetype = (sen Der as Button).
    
            Content.tostring (); If you need to share files, prompt the user to select the file if (_sharetype = "Share Image" | | _sharetype = "Share File" | | _sharetype = "Share Wi Th deferral ") {bool unsnapped = (applicationview.value!= applicationviewstate.snapped) | |
                Pplicationview.tryunsnap ()); if (unsnapped) {Fileopenpicker Filepicker = nEW Fileopenpicker {ViewMode = pickerviewmode.list, Su
                        Ggestedstartlocation = pickerlocationid.pictureslibrary, Filetypefilter = {"*"}
    
                    Filetypefilter = {". jpg", ". png", ". bmp", ". gif", ". tif"}};
                    _selectedfiles = await filepicker.pickmultiplefilesasync (); if (_selectedfiles.count > 0) {//pop-up share panel to begin shared operations D
                    Atatransfermanager.showshareui (); }} else {//pop-up share panel to begin shared operations Datatra
            Nsfermanager.showshareui (); The Demo private void Sharetext (Datatransfermanager DTM, Datarequestedeventargs args for the shared text) ) {Datapackage datapackage = args.
            Request.data; Datapackage.propErties.
            title = "title";
            DataPackage.Properties.Description = "Description";
        Datapackage.settext ("Detailed content to be shared");
        ///share the Demo private void Sharelink (Datatransfermanager DTM, Datarequestedeventargs args) {Datapackage datapackage = args.
            Request.data;
            DataPackage.Properties.Title = "Title";
            DataPackage.Properties.Description = "Description";
        Datapackage.seturi (New Uri ("http://webabcd.cnblogs.com")); //Shared photo demo (see the "Asynchronous shared Demo" of this example for sharing pictures) private void Shareimage (Datatransfermanager DTM, Data Requestedeventargs args) {datapackage datapackage = args.
            Request.data;
            DataPackage.Properties.Title = "Title";
    
            DataPackage.Properties.Description = "Description"; Share the first file in all selected files (assuming it is a picture) randomaccessstreamreference Imagestreamref = Randomaccessstreamreference.createfro Mfile (_selectEdfiles.first ());
            DataPackage.Properties.Thumbnail = Imagestreamref;
        Datapackage.setbitmap (IMAGESTREAMREF);
        Demo private void Sharefile for shared files (Datatransfermanager DTM, Datarequestedeventargs args) {Datapackage datapackage = args.
            Request.data;
            DataPackage.Properties.Title = "Title";
            DataPackage.Properties.Description = "Description";
        Datapackage.setstorageitems (_selectedfiles);
        ///shared HTML Demo private void sharehtml (Datatransfermanager DTM, Datarequestedeventargs args)
            {String localimage = "Ms-appx:///assets/logo.png";
            String htmlexample = "<p><b>webabcd</b></p>"; Add the necessary headers for the HTML to be shared to ensure normal HTML sharing operations String Htmlformat = Htmlformathelper.createhtmlformat (htmlexample
    
            ); Datapackage datapackage = args. ReQuest.
            Data;
            DataPackage.Properties.Title = "Title";
            DataPackage.Properties.Description = "Description";
    
            Datapackage.sethtmlformat (Htmlformat); Set local image data (if the HTML you want to share contains local images, you can only share it by this method) Randomaccessstreamreference Streamref = Randomaccessstreamrefere nCE.
            Createfromuri (New Uri (localimage));
    
            Datapackage.resourcemap[localimage] = Streamref; 
            * * The following shows how to share the user-selected HTML * in WebView (see also: Controls/webview/share.xaml *
            Datapackage datapackage = webview.datatransferpackage;
    
            Datapackageview Datapackageview = Datapackage.getview (); if ((Datapackageview!= null) && (DataPackageView.AvailableFormats.Count > 0)) {da
                TaPackage.Properties.Title = "Title";
                
                DataPackage.Properties.Description = "Description"; Args.
   Request.data = Datapackage;         /////shared Demo private void Sharecustomdata for custom data (Datatransfermanager DTM, Datarequestedeventargs args) {datapackage datapackage = args.
            Request.data;
            DataPackage.Properties.Title = "Title";
    
            DataPackage.Properties.Description = "Description";  Specifies the custom data that you want to share, the first parameter is the format ID of the custom data (note: The standard format ID is enumerated in Windows.ApplicationModel.DataTransfer.StandardDataFormats)// To allow custom data to be shared properly, you need to configure the custom format IDs in the shared targets declaration in package.appxmanifest, as well as sourcetarget the custom format IDs in the Datapack Age.
        SetData ("Http://webabcd/sharedemo", "Custom Data"); ///asynchronous Shared Demo (in scenarios where shared content takes a long time to compute, you should use asynchronous sharing) private void sharewithdeferral (Datatransfermanager DT M, Datarequestedeventargs args) {datapackage datapackage = args.
            Request.data;
            DataPackage.Properties.Title = "Title";
    DataPackage.Properties.Description = "Description";
            DataPackage.Properties.Thumbnail = Randomaccessstreamreference.createfromfile (_selectedfiles.first ()); By delegating to provide shared data, when a user clicks on a shared target, the delegate is invoked to not immediately provide shared data, but to wait until the user clicks on the shared target and then asynchronously prepares the data Datapackage.setdataprovider (Standardd Ataformats.bitmap, Providerrequest => this.
        Ondeferredimagerequestedhandler (Providerrequest, _selectedfiles.first ())); }//The user clicks on the shared target and calls this method private async void Ondeferredimagerequestedhandler (Dataproviderrequest provider Request, Storagefile imagefile) {//Get dataproviderdeferral to begin asynchronous processing, that is, to allow calls to the await method Da after this
            Taproviderdeferral deferral = providerrequest.getdeferral ();
    
            Inmemoryrandomaccessstream Inmemorystream = new Inmemoryrandomaccessstream (); try {//Reduce the user-selected picture by one times, and then share irandomaccessstream ImageStream = await imagefile.
                Openasync (Fileaccessmode.read); Bitmapdecoder Imagedecoder = await bitmapdecodEr.
                Createasync (ImageStream);
                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 ();
    
                Stop for 3 seconds to simulate long time task await task.delay (3000);
            Providerrequest.setdata (Randomaccessstreamreference.createfromstream (Inmemorystream)); finally {//notification datapackage has finished preparing the shared data deferral.
            Complete (); }
        }
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.