In Windows 10 platform, a new drag-and-drop functionality was introduced to Windows Universal apps for scenarios such as dragging image or document from your local machine straight into your app. It allows us developers to support more intuitive experiences. Drag and drop is a good way to transfer data within an application or between applications using a standard gesture.
Let’s see how simple it is to drag and drop image from your local system desktop into your Windows 10 Universal apps.
Steps:
Create new Windows 10 blank project and give suitable name.
Open your MainPage.XAML page and go to xaml code area in that create one StackPanel and allow drop property to true. Attach an event handler to Drop and DropOver event. Which will be used to handle an event of dropping image or document on the stackpanel. DropOver will be used to allow image copying while it's dragged over the stackpanel.
Add an Image object inside to show the image which was dropped.
Full source code looks like the following,
- <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
- <StackPanel Drop="StackPanel_Drop" DragOver="StackPanel_DragOver" AllowDrop="True" Background="#FF6C5C5C" BorderBrush="#FF3619F1" Margin="0,0,0,410"> </StackPanel>
- <Image x:Name="dragedImage" Margin="0,235,0,0"></Image>
- </Grid>
Now go to code behind page and write the following code in drop and dragover event handler.
- private async void StackPanel_Drop(object sender, DragEventArgs e)
- {
- if (e.DataView.Contains(StandardDataFormats.StorageItems))
- {
- var items = await e.DataView.GetStorageItemsAsync();
- if (items.Any())
- {
- var storeFile = items[0] as StorageFile;
- var bitmapImage = new BitmapImage();
- bitmapImage.SetSource(await storeFile.OpenAsync(FileAccessMode.Read));
- dragedImage.Source = bitmapImage;
- }
- }
- }
- private void StackPanel_DragOver(object sender, DragEventArgs e)
- {
- e.AcceptedOperation = DataPackageOperation.Copy;
- }
When image is being dragged over the stackpanel the DragOver event handler will be fired in that event. I am going to allow copying the dragged image.
When the photo gets dropped the drop event will be fired and here I will take it from the StorageItems collection and set the Source for dragedImage image.
You can set the Caption also for better user experience for that change the dragover event code like the following,
- private void StackPanel_DragOver(object sender, DragEventArgs e)
- {
- e.AcceptedOperation = DataPackageOperation.Copy;
- e.DragUIOverride.Caption = "You are dragging a image";
- e.DragUIOverride.IsCaptionVisible = true;
- e.DragUIOverride.IsContentVisible = true;
- }
Now run the app and show the output like the following screen.
Drag the image into stackpanel.
After doped into the stackpanel.