UWP – Win10 – Files and Folders P2 – Drag drop elements.

27 בFebruary 2017

אין תגובות

In this post we will jump in the real world scenario while user might drag clipboard files over our application pane and we like to copy those files and use them in our application.

Drag-Drop:

A few technical details.

Your Dropping area (the place you attended to release the clipboard file)

Should looks like this:

<Grid  Height="100" Width="100" Background="Red" AllowDrop="True" DragOver="Border_DragOver" Drop="Grid_Drop"/>

 

I have 3 different parts here,

AllowDrop,

DragOver handling, & Drop handling.

Those are mandatory.

The dragOver implementation is kind of :

private void Border_DragOver(object sender, DragEventArgs e)

        {

            e.AcceptedOperation = DataPackageOperation.Copy;

        }

and the Drop implementation is depends on your application requirements of course.

For example to Play MP3 file you should use something like:

private async void Grid_Drop(object sender, DragEventArgs e)

        {

            if (e.DataView.Contains(StandardDataFormats.StorageItems))

            {

                var items = await e.DataView.GetStorageItemsAsync();

                StorageFile file = items.First() as StorageFile;

                StorageFolder current = ApplicationData.Current.LocalCacheFolder;

                localFolder.Text = current.Path;

 

                if (current.GetFileAsync(file.Name) == null)

                {

                    await file.CopyAsync(current);

                }

                MediaElement player = new MediaElement();

                player.SetSource(await file.OpenAsync(FileAccessMode.Read), "mp3");

                player.Play();

            }

        }

Alternatively, for copying images you should use:

public ObservableCollection<BitmapImage> Images { get; set; } = new ObservableCollection<BitmapImage>();

 

and on Xaml Side- (or Similar)

 

<ListBox ItemsSource="{x:Bind Images}" Height="250" Name="imgs" AllowDrop="True"  

         Drop="imgs_Drop" DragEnter="imgs_DragEnter">

            <ListBox.ItemTemplate>

                <DataTemplate>

        <Image Height="100" Width="100" Source="{Binding}" Stretch="UniformToFill"/>

                </DataTemplate>

            </ListBox.ItemTemplate>

            <ListBoxItem/>

        </ListBox>

 

In both cases important thing is to follow that for using the files from the app I where must copied the files into local storage

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *