UWP: Clipboard

Starting with Windows 10 you can implement clipboard operations not just for desktop but also for all Windows 10 devices.

I already published the post about Drag and Drop functionality where we used DataPackage class in order to prepare data for sending to external applications and DataPackageView class to get data which was dragged from external source. In case of Clipboard we need to use the same approach but instead of event handlers we should implement content menus with standard commands there.

Let’s see how to implement Paste functionality. I am going to use the same application which I used in Drag and Drop post because we can use the same code. I am going to allow Paste feature for images, so I will show images in ListView and I need to implement a simple MenuFlyout:

 <ListView Margin="50" Name="listView" RightTapped="listView_RightTapped" IsRightTapEnabled="True">
<ListView.Resources>
 <MenuFlyout x:Name="menuFlyout">
 <MenuFlyout.Items>
 <MenuFlyoutItem Name="pasteItem" Text="Paste" Click="MenuFlyoutItem_Click"></MenuFlyoutItem>
 </MenuFlyout.Items>
 </MenuFlyout>
</ListView.Resources>
<ListView.ItemTemplate>
 <DataTemplate>
 <Grid>
 <Image Source="{Binding Source}" Width="200" Margin="10"></Image>
 </Grid>
 </DataTemplate>
</ListView.ItemTemplate>
</ListView>

You can see that I declared MenuFlyout like a resource of ListView. MenuFlyout class doesn’t allow to show menu automatically. So, I allowed right click for my ListView and implemented RightTapped event handler in the following way:

 private async void listView_RightTapped(object sender, RightTappedRoutedEventArgs e)
{
 var format = Clipboard.GetContent().Contains("FileDrop");
 pasteItem.IsEnabled = format;
 menuFlyout.ShowAt(listView, e.GetPosition(null));
} 

In order to implement a better UX I check if any files are available and enable or disable menu item.

Finally, if user selects Paste menu item I use Clipboard class in order to get all available files and prepare them to show in ListView:

 private async void MenuFlyoutItem_Click(object sender, RoutedEventArgs e)
{ 
 var files = await Clipboard.GetContent().GetStorageItemsAsync();
 List<BitmapItem> items = new List<BitmapItem>();
 foreach (StorageFile file in files)
 {
 try
 {
 BitmapImage bi = new BitmapImage();
 bi.SetSource(await file.OpenAsync(FileAccessMode.Read));
 items.Add(new BitmapItem() { Source = bi });
 }
 catch { }
 }
 listView.ItemsSource = items;
} 

You can see that we used the same code like in the Drag and Drop post. We changed just the first line of code – we used Clipboard class to get DataPackageView.

Therefore you can see that Drag and Drop and clipboard features are better to implement together because you can use the same approach and these features are now universal.