Silverlight 4 dropping, rightclick, printing demo

9 12 2009

For my presentation one week ago, I showed two demos. I thought I’d share one of those with you now. It’s calles “What we talked about at the christmas party” and highlights in a simple way, three new features of Silverlight 4; Dropping, right clicking and printing.


Let’s begin!

Let’s start by determining what we want this demo to achieve. First, I wanted to do a demo from the ground up, no prewritten code or anything. If I can do it, so can you.  I also wanted to show three things.

1. Silverlight now handles drag-dropping from Windows Explorer into a given browser.

2. Silverlight now handles true right click event handling. We want to deisplay something NOT associated with showing a context menu.

3. Silverlight can now print pages. The printing is customizable and we can choose which parts of our program we want to print.

Now that we know what we want, let’s start looking at some code. This is the XAML code used in our demo:

<Grid x:Name="LayoutRoot" Background="White" Margin="20">
        <Border BorderBrush="Black" BorderThickness="8"> 

                <Grid Name="PrintArea"> 


                <Button /> 


These are the controls we’re going to use. Let’s start with the drag-n-dropping.

— Drag and Drop —


                <Grid Name="PrintArea"> 
<Canvas Name="myCanvas" AllowDrop="True" Drop="myCanvas_Drop" Height="Auto" Width="Auto" Background="Transparent"


Here we’re adding two important properties; AllowDrop and Drop. The first is a property allowing us to drop stuff on this control. The second is a event handler for when we actually drop something. Both these are needed to be able to drag-drop.
The event handler code looks like this:

private void myCanvas_Drop(object sender, DragEventArgs e)
            IDataObject dataObject = e.Data;
            var files = (FileInfo[])dataObject.GetData(DataFormats.FileDrop);

            //Iterate throgh the files
            foreach (FileInfo file in files)
                if (file.Extension.Equals(".png", StringComparison.InvariantCultureIgnoreCase)
                || file.Extension.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase)
                || file.Extension.Equals(".jpeg", StringComparison.InvariantCultureIgnoreCase))

               … [IMAGE LOGIC HERE] …



What happens here is this: the image is caught and verified by the handler. We then create an image from the file and add it to our Canvas control. The code for creating the image looks like this:

Stream stream = file.OpenRead();
                    string name = file.Name;
                    Point dropPoint = e.GetPosition(myCanvas);

                    BitmapImage bmi = new BitmapImage();
                    Image myImage = new Image();
                    myImage.Source = bmi;
                    myImage.Width = 192;
                    myImage.Height = 120;
                    myImage.Stretch = Stretch.UniformToFill;
                    myImage.MouseRightButtonDown += new MouseButtonEventHandler(myImage_MouseRightButtonDown);
                    myImage.MouseRightButtonUp += new MouseButtonEventHandler(myImage_MouseRightButtonUp);

                    Border border = new Border();
                    border.BorderBrush = new SolidColorBrush(Colors.Black);
                    border.BorderThickness = new Thickness(10, 10, 10, 30);
                    border.Child = myImage;

                    TextBlock titel = new TextBlock();
//To remove file extension
                    titel.Text = name.Remove(name.Length -4);
                    titel.FontSize = 18;
                    titel.SetValue(Canvas.LeftProperty, Convert.ToDouble(10));
                    titel.SetValue(Canvas.TopProperty, Convert.ToDouble(130));
                    titel.Foreground = new SolidColorBrush(Colors.White);

                    Canvas imageCanvas = new Canvas();

                    imageCanvas.SetValue(Canvas.LeftProperty, dropPoint.X);
                    imageCanvas.SetValue(Canvas.TopProperty, dropPoint.Y);


We base our image file on the stream sent by the event handler. As seen on the third row, we can also find out where the file was dropped, which later allows us to create our image at that precise spot. I chose to include a border and title for my images, but this part is up to you how you want to present it.

Drag Drop Silverlight

— Right Click —

I earlier wrote a quick snip on how to enable this in SL4. This is a real easy trick. As you saw in my previous code block, I added handlers for myImage.MouseRightButtonUp and Down. The code I used in the handlers is just as simple:

void myImage_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
            MessageBox.Show("Right Click support says hi!");

        void myImage_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
            e.Handled = true;

Of course you can put anything you want in the first method but I only wanted to illustrate that I could bind to the right mouse button. The important part to remember is that the MouseRightButtonDown event has to be handled as well. Otherwise, the default Silverlight menu will show up uninvited.

Right click Silverlight

— Printing —


This is where my XAML gets a bit hairy.

<Grid x:Name="LayoutRoot" Background="White" Margin="20">
        <Border BorderBrush="Black" BorderThickness="8"> 

                <Grid Name="PrintArea">
                        <ImageBrush ImageSource="bg.jpg" />
                    <Canvas Name="myCanvas" AllowDrop="True" Drop="myCanvas_Drop"> 

                <TextBlock HorizontalAlignment="Center" Margin="5" Foreground="White" FontFamily="Trebuchet MS" FontSize="40" Height="50" VerticalAlignment="Top" >
                        What we talked about at the Christmas Party

                <Button Name="Printbutton" Content="PRINT" Click="Printbutton_Click" Height="100" VerticalAlignment="Bottom" Width="300" Margin="10" FontSize="24" /> 


You can see here that I added content to both my button and my textblock as well as a background inside the “PrintArea” grid. What I wish to achieve here is to only print the PrintArea grid. This is why the textblock and button are both outside the grid.

Printing in Silverlight

On the code side, I’ve hooked up a click-handler to the button to do the printing. This is the code:

public MainPage()

    printDocument.PrintPage += new EventHandler<PrintPageEventArgs>(printDocument_PrintPage);

PrintDocument printDocument = new PrintDocument();

        private void Printbutton_Click(object sender, RoutedEventArgs e)
            printDocument.DocumentName = "Julfesten";

        void printDocument_PrintPage(object sender, PrintPageEventArgs e)

            e.PageVisual = PrintArea;
            e.HasMorePages = false;


We create a new PrintDocument and when the button is clicked we give it a name and print it. A event handler catches this and sets two properties: PageVisual which controls which parts of a page are printed and HasMorePages which controls if we want one or more page results. This is really all you need to print a document from Silverlight. With this code, Only my canvas with background and all the pics I dragged into it will be printed. Not the border, button or textblock.

Printing Silverlight                           Voila! No button, border or text




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: