Drag and Drop in Silverlight 4

To enable drag and drop support on a Silverlight UIElement the AllowDrop property needs to be set to True (it is false by default). The Drop event can now be subscribed to, in which the dropped item(s) can be processed.

The example below allows a .jpg file to be dragged (from the desktop, Windows Explorer, etc.) and dropped onto the application. When the user drops a .jpg, the image is loaded and displayed.

<Grid x:Name="LayoutRoot"
        Background="Black"
        AllowDrop="True"
        Drop="LayoutRoot_Drop">
       
    <Image Name="imgPresenter"
            Stretch="UniformToFill"
            IsHitTestVisible="False" />
       
    <TextBlock HorizontalAlignment="Center"
                VerticalAlignment="Center"
                IsHitTestVisible="False"
                Foreground="#FFCBC3C3"
                FontSize="32"
                Opacity="0.33"
                Text="drag photo here"/>       
       
</Grid>

 

Code behind:

private void LayoutRoot_Drop(object sender, DragEventArgs e)
{
    if (e.Data != null)
    {
        // Get a list of the file(s) that the user has dragged & dropped
        FileInfo[] droppedFiles = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

        // If there is at least 1 file that has been dropped
        if (droppedFiles != null && droppedFiles.Length > 0)
        {
            LoadImage(droppedFiles.First());
        }               
    }
}



private void LoadImage(FileInfo imageFileInfo)
{
    if (imageFileInfo.Extension.ToUpper() != ".JPG")
    {
        MessageBox.Show("Only .jpg files are supported...");
    }
    else
    {
        // Load the image from disk
        BitmapImage source = new BitmapImage();
        source.SetSource(imageFileInfo.OpenRead());

        // Set the image being displayed to the new dropped one
        imgPresenter.Source = source;
    }
}

Add comment

Loading