RIA Development Center
Features Tips Events
Jon Galloway discusses the challenges and solutions to handling keyboard input in Silverlight including:
  • Silverlight not firing the KeyDown event for cursor (arrow) keys
  • The difference between Key and PlatformKey
  • The missing Key Enumeration
  • How to create a keyboard handler event
  • Read more
    See more tips
    Get regular email alerts when we publish new features!
    DevX RIA Development Update

    More Newsletters
    PHP Developers Don't Need Silverlight—Or Do They? (cont'd)

    Step 4: Create Dynamic XAML with PHP
    Now that all the pieces are in place, you can add the final code. In Step 2 you created some mouse events. In Step 3 you created some PHP that displays to your canvas area. You can probably guess what will happen next.

    For this demo, your control panel will have one and only one function: add colored dots. You have many options for doing this, but the one I'll cover here is the use of a URL string to pass a concatenated JavaScript variable. In summary:

  • Every time you click on a dot, the JavaScript will add a new value to a string.
  • That string will then be passed to your PHP script.
  • The PHP script explodes the string into an array.
  • Based on the array length and values, it will return a set of dots.

    To start, the createSilverlight.js file needs a bit of code. While colors can be passed as common names, I prefer working with hex values, which takes a little more work. As you saw earlier, the Fill.Color value returns a long. To convert that value to hex, add the following function (credit goes to Suyog Kale for posting this routine):

    function getFillColor(color)
    {
    	var fill = color;
    	if (fill < 0) {
    		fill = (16777216 + parseInt(fill));
    	}
    	fill = fill.toString(16);
    	if (fill.length > 6) {
    		fill = fill.substr(fill.length - 6);
    	}
    	while (fill.length < 6) {
    		fill = "0" + fill;
    	}
    	fill = "ff" + fill;
    	return fill;
    }

    Note the last addition to the string: "ff". Silverlight works with 8-digit hex values for color, comprised of the 6-digit value preceded by "ff".

    Replace the dropDots() function entirely with the following:

    var dotColors="";
    
    function dropDots(sender, mouseEventArgs)
    {
    	if (dotColors != "")
    	{
    		dotColors += ",";
    	}
    	dotColors += getFillColor(sender.Fill.Color);
    	createDisplayCanvas();
    }

    Note the new global var "dotColors".

    In the createDisplayCanvas() function, replace

    source: "drawDots.php",
    with
    source: "drawDots.php?colors=" + dotColors, 

    At this point, createSilverlight.js should look something like Listing 5.

    Listing 5: Completed createSilverlight.js

    function createControlPanel()
    {
    	Silverlight.createObjectEx({
    		source: "controlPanel.xaml",
    		parentElement: document.getElementById("dotControlPanel"),
    		id: "slControlPanel",
    		properties: {
    			width: "100%",
    			height: "100%",
    			inplaceInstallPrompt:true,
    			version: "1.0"
    		}
    	});
    }
    
    
    if (!window.Silverlight) 
    	window.Silverlight = {};
    
    Silverlight.createDelegate = function(instance, method) {
    	return function() {
    		return method.apply(instance, arguments);
    	}
    }
    
    var dotColors="";
    
    function dropDots(sender, mouseEventArgs)
    {
    	if (dotColors != "")
    	{
    		dotColors += ",";
    	}
    	dotColors += getFillColor(sender.Fill.Color);
    	createDisplayCanvas();
    }
    
    function createDisplayCanvas()
    {
        Silverlight.createObjectEx({
    	source: "drawDots.php?colors=" + dotColors,
    	parentElement: document.getElementById("dotDisplayCanvas"),
    	id: "slDisplayCanvas",
    		properties: {
    			width: "100%",
    			height: "100%",
    			inplaceInstallPrompt:true,
    			version: "1.0"
    		}
    	});
    }
    
    function getFillColor(color)
    {
    	var fill = color;
    	if (fill < 0) {
    		fill = (16777216 + parseInt(fill));
    	}
    	fill = fill.toString(16);
    	if (fill.length > 6) {
    		fill = fill.substr(fill.length - 6);
    	}
    	while (fill.length < 6) {
    		fill = "0" + fill;
    	}
    	fill = "ff" + fill;
    	return fill;
    }

    Replace the contents of drawDots.php entirely with Listing 6.

    Listing 6: Completed drawDots.php

    <?
    header('Content-type: text/xml');
    ?>
    
    <?
    	$arrColors = explode(",",$_GET["colors"]);
    	srand(time());
    ?>
    
    <Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="resultCanvas">
    <Canvas x:Name="Layer_1" Width="640" Height="80" Canvas.Left="0"
    Canvas.Top="0"> <? $n = 0; foreach ($arrColors as $c) { $n++; $lft = (rand()%530); $top = (rand()%370); echo('<Ellipse x:Name="Ellipse_' . $n . '" Width="100" Height="100"
    Canvas.Left="' . $lft . '" Canvas.Top="' . $top . '" Stretch="Fill" Fill="#' . $c . '"/>'); } ?> </Canvas> </Canvas>

    As you can see, mouse events in the XAML file trigger a JavaScript routine which concatenates a global variable with the fill color of the selected dot. It then redraws the canvas by calling the createDisplayCanvas() function, which passes this string via GET to the PHP page.

    The new PHP script explodes the GET string into an array, which can then be looped through via foreach. As an added bonus, I've added a bit of randomness to the equation by also setting Canvas.Left and Canvas.Top to random values within the Ellipse XAML echo. This serves no practical function whatsoever other than, hopefully, to stimulate the imagination a bit and induce more creative and interesting demonstrations of the technique.

    The final result can be viewed here: www.justinwhitney.com/slphpdemo/PHPdemo.htm. You can also download a zip of the final source code here.

    Where to Go From Here
    This walkthrough barely scratches the surface of what you can do with Silverlight and PHP. Below are a few additional resources for investigating the topic further. If you come up with something cool, post it and send us a link.

  • Silverlight Downloads

  • Delivering Parameterized Silverlight Content with PHP

  • Silverlight with PHP

  • Flickr Example

  • Silverlight / PHP / MySQL / Linux / Firefox Demo

  • Instantiating a Silverlight Plug-in (Using CreateSilverlight.js and Silverlight.js)

  • Silverlight QuickStart: Scripting and Mouse Events

  • Binding a XAML Application to DataBase Data

  • * This article was commissioned by and prepared for Microsoft Corporation. This document is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.


    Page 3 of 3
    Justin Whitney is a regular contributor to DevX.com and Jupitermedia. He currently lives in San Francisco, where he consults for leading high-tech firms and writes about emerging technologies.
    Previous Page: Steps 2 and 3  
    Page 1: Step OnePage 3: Step 4 and Where to Go From Here
    Page 2: Steps 2 and 3 
    Want to know who achieved gaming stardom? Keep checking RIGHT HERE! In the upcoming weeks, we will be showcasing some of the hottest next-gen games using Silverlight 2. You will be able to play them, too! Winners will be announced on June 30, 2008 so be sure to tune in. Happy Gaming!