A new feature of Windows 8.1 is that developers can render the XAML tree to a bitmap. This can be useful in exposing a screenshot of a part of an application with the image Share contract. Note that Windows 8.1 supports sharing a screenshot of any app through a new Share charm option. This is slightly more specific and also lets you control properties like Title.

In order to make this happen, you have to go through a few hoops. Here is a sample event handler that wires up the pieces together including converting to a PNG image to bring the file size down. See MSDN’s “How to share an image” article for configuration.

In this case, we have a ScrollViewer in an ListView control (it’s used in a continuous document viewing section of an app). The method shares what is currently visible on the screen.

private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
var scrollViewer = RecurseChildren<ScrollViewer>(lvImages).FirstOrDefault();

if (scrollViewer != null)
{
DataRequest request = e.Request;
request.Data.Properties.Title = "Clip from an app";

DataRequestDeferral deferral = request.GetDeferral();

try
{
var bmp = new RenderTargetBitmap();
await bmp.RenderAsync(scrollViewer);

var pixelBuffer = await bmp.GetPixelsAsync();

var reader = DataReader.FromBuffer(pixelBuffer);
var bytes = new byte[pixelBuffer.Length];
reader.ReadBytes(bytes);

var randomAccessStream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, randomAccessStream);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, (uint)bmp.PixelWidth, (uint)bmp.PixelHeight, 96, 96, bytes);
await encoder.FlushAsync();
await randomAccessStream.FlushAsync();

request.Data.SetBitmap(RandomAccessStreamReference.CreateFromStream(randomAccessStream));
}
finally
{
deferral.Complete();
}
}
}

Here is an example from my Army Field Manuals app. Note that the share item doesn’t include the app border, which is handy in this case:

share_rendertargetbitmap

Additional references used:


Note: This blog post is based on Windows 8.1 RTM and Visual Studio 2013 RC.