Windows 8 sharing the right way

Posted by on

For the love of god SetText()

In Windows 8 the share charm can be a very powerful concept allowing selections of data to be easily sent between apps with a nice user experience. Working on the Windows 8 platform for some time I have seen a lot of apps with poorly implemented share charms and this really annoys me.

The first thing to do when implementing a share contract is to subscribe to the DataRequested event on the current view's DataTransferManager. This event will be fired when ever the share charm is invoked while you app is running.

var transferManager = DataTransferManager.GetForCurrentView();
transferManager.DataRequested += OnDataRequested;

From this event you get access to a DataRequest object where you can set all of your properties to share to other apps. Below is both a bad and good example of implementing this event. I have seen too many apps using the bad example out of developer laziness or lack of understanding about what to share.

This is a bad example of sharing.

public void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
    args.Request.Data.Properties.Title = "My awesome app!";
    args.Request.Data.Properties.Description = "I CAN HAZ FACEBOOK SHARE FEATURE";

This is a good example of sharing.

In this example we will give our share a title, description as well as a custom share test, a thumbnail and an image of the awesome emotion.

public async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
    args.Request.Data.Properties.Title = "Share Tester!";
    args.Request.Data.Properties.Description = "I'm going to share Text, Image, Thumb, Link and StorageItems.";

	//Set the text content for the share target to use
    args.Request.Data.SetText("Check this out, sharing with the Share Tester");

    //NOTE: to use await you will need to call args.Request.GetDeferral() then call Complete() on the deferral
    //Get the image file you want to share
    StorageFile imageFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("test.png");

    var ranAccStreamRef = RandomAccessStreamReference.CreateFromFile(imageFile);

    //Set an image for the share target
	//Set the thumbnail for the image (can set this to a different image if you have one)
    args.Request.Data.Properties.Thumbnail = ranAccStreamRef;

	//Some share targets prefer images as a StorageFile :S
    args.Request.Data.SetStorageItems(new List<StorageFile> { imageFile });

    //Set a link to share
    args.Request.Data.SetUri(new Uri(""));

This is what you get in the share charm

This is what we get sharing to Facebook

This is what we get sharing to Mail

If you're looking for more information about sharing checkout the MSDN Sharing content Quickstart or some of the other pages related to sharing.