Tuesday, February 5, 2013

Sharing in a Windows 8 App (Part 1)


Sharing is a unique feature in Windows 8.  It is a key differentiator from the iPAD.  Windows 8 Apps declare themselves as one of the following:
a)      Able to share data,
b)      Able to receive shared data, or
c)       Both

Most of the time, your Windows 8 Apps will be sharing simple data.  These data types include:
a)      Plain text
b)      RTF
c)       HTML
d)      Bitmaps
e)      Files
f)       URIs

The general idea here is that you don’t declare a format.  Your app just states that it is able to share plain text, or that it is able to share bitmaps, etc, and you allow the target apps to make sense of the data.  There is no strict sense of contracts, the way that an Interface might enforce one.  All that your app is declaring is that it is able to share data, and not that it can perform a certain task.

In order to handle outbound sharing, you will need to use the DataTransferManager to tell Windows that your app wants to be asked for shared data.  When the user selects the Share charm, your app will be called, and it will have the opportunity then to provide or share data.

The Request Handler is registered globally, and the first thing you would need to do is to dereference the current page.  We will do this using an interface.  When sharing its data, your app will first need to provide metadata about the data that it is sharing, including the title and description of the data, before providing the actual data.

For this demo, we will be sharing some basic text.    What I have done below is create a simple XAML design surface with a TextBlock and a TextBox with some sample text in it.  The user will be able to enter any test they want, bring up the Share charm, say that they wish to share the text, and that text will be shared by any application that understands text.


The first thing we have to do is go into the App.xaml code and register the handler.  In the OnLaunched event  handler, at the very end,  we write the following line of code:



We would write the method stub for this new method as follows:


We implement the new DataRequested event handler as follows:



So far, we have discussed what Sharing in a Windows 8 app means.  We introduced the DataTransferManager, which we will need to tell Windows that your app wants to share data.  We built a simple XAML design surface with sample text to share.   And we implemented the DataRequested event handler in the App.xaml code.  In Part 2 we complete the rest of the code.


No comments:

Post a Comment