Silverlighting Your PHP, Part 2: Hijacking XAML From Expression Blend

DZone 's Guide to

Silverlighting Your PHP, Part 2: Hijacking XAML From Expression Blend

· Web Dev Zone ·
Free Resource

In Part One of this series, “Silverlighting Your PHP: Adding Silverlight With Nothing But Notepad”, you learned how to add some Silverlight to your PHP app by using PHP to generate XAML code. Using some very simple XAML, you not only generated a series of menu options, but also added some basic animation and a dropshadow effect.

One thing that app demonstrated, aside from how to create a potentially elegant menu, is how tricky it is to code XAML by hand without any development tools. Free, yes. But still difficult, with a lot of trial and error. That’s why in Part 2 of this series, you’ll step it up a notch by incorporating Expression Blend into your workflow.


Microsoft released the Expression Suite in conjunction with Silverlight as a tool for enabling side-by-side development. In other words, as the graphics team designs the user interface, the developers can build out the code in tandem using Visual Studio. The entire workflow was architected to decouple code from design, to increase productivity in an Agile workplace.

But here’s the interesting thing for PHP developers: the design side of the equation doesn’t just produce static graphics. One of the primary components of the suite, Expression Blend, gives app developers a lot of functionality right out of the gate. In addition to building out a vector-based user interface, you can add timeline-based animation without writing a single line of code.

In this example, you’ll learn how to use Expression Blend as a starting point for a more stylized UI, which you’ll populate using PHP code. First you’ll use Expression Blend to create your XAML code, then you’ll then break it apart and incorporate PHP to add your dynamic elements.

This walkthrough emulates a highly responsive record-detail selection action. You’ll keep both record and detail simple by creating an “Employee List” that consists of Name and Job Title. As in the previous walkthrough, you’ll use an array rather than database calls. Don’t want to get too fancy here.


Step One: Classic PHP Employee List

Before diving into Expression Blend, take a moment to create your placeholder for the XAML you’ll ultimately be creating. Save the following to PHPEmpList.php. This will serve as the landing page.

<title>Silverlight PHP Employee List</title>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript" src="xamlFunctions.js"></script>
<style type="text/css">
.empList {
height: 480px;
width: 640px;

<p>Just PHP:</p>
<div id="empListPlain" class="empList">
// Database fetch goes here. For this example,
// use a multidimensional array.
$employees =
array('id'=>1, 'name'=>'Apollo', 'jobtitle'=>'God of Music'),
array('id'=>2, 'name'=>'Aphrodite', 'jobtitle'=>'Goddess of Love'),
array('id'=>3, 'name'=>'Mars', 'jobtitle'=>'God of War'),
array('id'=>4, 'name'=>'Artemis', 'jobtitle'=>'Goddess of the Hunt') );
$n = 0;

foreach ($employees as $employee) {
echo('<p>' . $employee['name'] . ' : ' . $employee['jobtitle'] . '</p>');

<p>Silverlighted PHP:</p>
<div id="empListSL" class="empList">
<script type="text/javascript">


Before running this, add a couple of JavaScript files. One is the magic Silverlight.js file that you need for all Silverlight apps. You can find a copy here. The second is a short script to create your XAML object. Save the following code as xamlFunctions.js:

function createEmpList()
source: "createList.php",
parentElement: document.getElementById("empListSL"),
id: "slEmpList",
properties: {
width: "100%",
height: "100%",
version: "3.0"

if (!window.Silverlight)
window.Silverlight = {};
Silverlight.createDelegate = function(instance, method) {
return function() {
return method.apply(instance, arguments);


One last piece, create an empty doc and name it “createList.php”. You may have noticed this referenced in the object JavaScript. This will eventually contain your XAML. The nifty trick at play here is that the XAML doesn’t need to be created by a “.xaml” file. You can use PHP to generate your XAML and then reference the result by assigning it as the source for your Silverlight object, as is being done here.

If you run PHPEmpList.php now, you’ll see a pretty basic page (Figure 1). This would be your “Before” picture. Note that this example already includes the Silverlight object at the bottom half of the page, though this is currently empty.



Step Two: Create a XAML Front-End

Download Expression Blend 4, currently in Preview. This includes Silverlight 4 Runtime, which you can’t download or install without a .NET 4 development tool, all of which are in Beta at the time this was written. By using Expression Blend 4, you’ll be able to run Silverlight 4 apps locally. However, for this walkthrough you’ll be sticking with Silverlight 3 features so you can go live with your examples should you desire.

To start, create a new “Silverlight 4 Application + Website” and call it “PHPEmpList”.



One of the first things you’ll notice, assuming you’ve never used Expression Blend before, is that this is a hybrid of design and development, hence the name. While you can’t create extremely complex graphics content, which is the domain of Expression Design, or do any .NET coding, which is the purpose of Visual Studio, you can still get quite a bit done. More to the point, you can create the XAML you’ll need for your PHP app.

Instead of defaulting to a blank white canvas, add some design elements. One way to do this is to draw a rectangle over the canvas using the Rectangle control on the left (see Figure 3). To keep it simple, draw a rectangle over the top fifth of the canvas and color it dark grey. Then draw another rectangle over the bottom fifth of the canvas and color it light grey.



On the boundary between the two, add an Ellipse control in the same way. Try to get it to come out about 80 height and 150 width. If you can’t quite get it using the tool, you can set the dimensions directly using the properties panel on the right. You can also change its fill color here, for example to a lovely robin’s egg blue.

Select the Textblock tool from the toolbox to the left of the controls.



Add a Textblock to the center of your ellipse and give it some placeholder content, such as “Placeholder.” You can set Text Properties on the right. Use a font size of 10 and the font family of your choice.



It might also be helpful to center the text, which you can do using the Paragraph properties on the right.



Select both the Ellipse and the Textblock and group them by selecting Object -> Group Into -> Grid (see Figure 7). This nests the XAML for those two objects inside a Grid container. This is not strictly required for adding interactivity, but makes for nicer organization. This new container will also serve as a prototype for the PHP you’ll create later.



These ellipses will also serve as selectors for each of your “employees”, with the detail, in this case Job Title, appearing in a central box below. To create that box, add another Rectangle object to the center of the canvas. Select it with the Selector tool (also known as the arrow at the top of the toolbox on the left) to reveal its control points. Notice the upper left corner of the rectangle has two additional control points. Drag them and see what happens. The result should be similar to Figure 8.



As with the Ellipse, drag a Textblock onto your new rectangle and fill it with placeholder text, such as “Placeholder text”. Center it and give it a font size of 24. You should have something like Figure 9. This is the one object you’ll want to name, so call it “bubbleText”. Also be sure to group the Rectangle and Textblock together.



Now that you have a basic UI, now’s a good time to look at the XAML you’ve created. Under View -> Active Document, you’ll notice a few options for organizing your workspace. These will be familiar to anyone used to WYSIWYG editors, except that in this case the code being generated is XAML. Go to “Split View” so you can see the result up to this point.

Before going further, this would be the perfect point for a quick sanity check. Build and Run the code as is. You should see your Silverlight app in your browser.



Copy and paste your new XAML code into createList.php. Reload PHPEmpList.php.

See anything wrong? You’ll probably see nothing at all. At all. That’s because the XAML is not showing up. Took another look at your XAML code. You’ll see two things created by Expression Blend that won’t work in this type of architecture.

Expression Blend nests everything in a “UserControl” object. Edit every instance of “UserControl” to be “Grid” instead.

Expression Blend also adds a Class reference in that same object. This is a reference to the compiled code created by the IDE. In fact, if you look at your Project files, you’ll see that your code has been conveniently capsulated in a .xap container inside the ClientBin folder of PHPEmpListSite. Expression Blend makes it extremely easy to deploy your Silverlight project in this way. However, since you’re circumventing this elegant deployment process at the moment, just remove the following line:



Your createList.php file should look something like this:

Width="640" Height="480">

<Grid x:Name="LayoutRoot" Background="White">
<Rectangle Fill="#FFBCBCBC" Stroke="Black"/>
<Rectangle Fill="#FF565656" Height="67" Stroke="Black" VerticalAlignment="Top"/>
<Grid HorizontalAlignment="Left" Height="80" Margin="21,23,0,0" VerticalAlignment="Top" Width="143">
<Ellipse Fill="#FF4F8DC8" Stroke="Black" />
<TextBlock HorizontalAlignment="Left" Height="28" Margin="19,31,18,21" TextWrapping="Wrap" Text="Placeholder" VerticalAlignment="Top" Width="106" FontSize="13.333" FontWeight="Bold" FontFamily="Trebuchet MS" TextAlignment="Center"/>
<Grid Margin="146,152,165,129">
<Rectangle Fill="White" RadiusY="39" RadiusX="39" Stroke="Black"/>
<TextBlock x:Name="bubbleText" FontSize="24" FontFamily="Trebuchet MS" Margin="18,25,27,24" TextAlignment="Center" TextWrapping="Wrap" Text="Placeholder text."/>


Reload PHPEmpList.php again and you should now see the Silverlight object at the bottom of the page as it appeared in Figure 10. (If nothing shows up, don’t forget to make sure you copied the Silverlight.js file.)

Step Three: Create XAML Animation

Jump back into Expression Blend and take a look at the Objects and Timeline panel where your new objects have been appearing. At the top of the panel, you’ll see a dropdown for Storyboards. Many find the process of creating Storyboards to be less than intuitive in Expression Blend. In addition to the Controls available to use on your canvas, like Rectangles, Sliders, Listboxes, etc, you have access to several prebuilt Behaviors. These Behaviors add interactivity to your Silverlight app by allowing you to add Triggers or control your Storyboard, for example.

However, none of these Behaviors actually create the Storyboards. To do that, you’ll use the Objects panel. In this case, you’ll animate the display box in the middle of the canvas, so select that, then click the “+” sign to create a new Storyboard.



You should see a new timeline, measured in seconds, to the right of your objects (see Figure 12). While you’re in “record” mode like you are now, you can build your animation by creating keyframes over time. For this example, you’ll want the display box to bounce into being with the job title of the person selected, eventually settling into the size you’ve created it. Your animation should last one second.


Since this is the ending state of the animation, jump ahead to one second on the timeline and hit the keyframe icon, as in Figure 13. Nothing else needs to be done here.


Next go back to 0 seconds and add another keyframe.



This time you’ll change the size by adjusting the RenderTransform Property. On the right, expand the Transform panel and find the RenderTransform tab. Since this is a Double data type, you’ll see your grid’s current values of 1 for both X and Y, indicating 100% for width and height. Change these both to 0, as you can see happening in Figure 15.



To test the animation, hit the Play icon next to the Storyboard. You should see your center box grow from nothing to full size. It’s an interesting start, but needs a little something.

Expand your grid container. Having just recorded a change in the RenderTransform property, you’ll see a new object in your group: RenderTransform. Select it.



In Expression Blend you have the option of defining not just a change in property over time, but how that property changes over time. This change, or interpolation, is graphed on a KeySpline, which graphs the value of x over time. You can change this graph manually or you can use one of the prebuilt EasingFunctions, which graph how the property “eases into” its destination value or “eases out of” its initial value.

Select the EasingFunction tab and look at the dropdown. Expression Blend 4 offers a lot of ready-made graphs that describe your property’s interpolation. The best thing is that choosing any one of these drops in the necessary XAML to make it happen. From this list, choose “Bounce” under the “In” column.



You don’t want to go nuts with the animation here, so change the Bounce values to something subtle, like Bounces = 1 and Bounciness = 1.



Now try playing the Storyboard again. That’s one bouncy box. Since you’re done creating the Storyboard, you can go ahead and close it.



Here’s one moderately confusing point for beginners: even though it felt like you were editing your grid container, you were only doing so in the context of the Storyboard. With the Storyboard closed, your grid goes back to the way it was before you began recording the animation. To finish the effect of your text bouncing out of nothingness (and to hide the text change when you add your PHP array), you should start with nothingness. So with the grid still highlighted, change the RenderTransform property again to 0, 0.



You have an animation, but you still need to kick it off somehow. You have a couple of ways you can do this.

Under the Assets tab on the top left, look at your available Behaviors. Expression Blend comes with several prebuilt behaviors that you can implement without writing a single line of code. In fact, you’ll also see a link to the Expression Gallery, where you can find more Behaviors.



If you were going to deploy this app as a .NET project, then you can just drop in one of these behaviors, “ControlStoryboardAction” for example, then choose MouseLeftButtonDown as the event (which should be the default) and “bubbleOut” as the Storyboard. And you’re done.



Expression Blend then links up the relevant assemblies, then compiles and packages the code you need to run your Silverlight app. And unless you were doing something fairly sophisticated, you would likely find all the functionality you needed available here, without ever opening the project in Visual Studio.

That said, the goal with this app is to generate the XAML through PHP rather than relying on the XAML packaged in the .xap file. That means triggering the animation using JavaScript.

But before adding that last bit, grab all of your newly created XAML code and copy that into createList.php, replacing that files current content.

Step Four: Chop it up and add PHP

In Step Two you had the chance to make some minor tweaks to generated XAML code in order to get it to work properly in this configuration. That was just a warmup. Now you have more code to play with, but the process is essentially the same, with the minor difference of incorporating your PHP.


A.              First, change UserControl to Grid. You have objects other than Grid to choose from, but for now stick with what you know. Also, with the addition of your Storyboard, Expression Blend created a “UserControl.Resources” container, so be sure to change that, as well (to “Grid.Resources”). You should see a total of four references that need to be replaced.

B.              Also near the top you’ll see a reference to several .NET assemblies. Fortunately, you can do without that, so get rid of it. The property in question should be line 4:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:im="clr-namespace:Microsoft.Expression.Interactivity.Media;assembly=Microsoft.Expression.Interactions"

C.              Delete the reference to “PHPEmpList.MainPage” in the next line.

D.             If you added that behavior in Figure 22 just for kicks, it will have created a Trigger in the XAML. Do a search on “Triggers”. If you find a container called “i:Interaction.Triggers” then delete the entire container and everything in it.


Sanity check: reload PHPEmpList.php and see what happens. If there’s anything wrong with the XAML then nothing will show up and you won’t get any error message (yeah, helpful that). But if you see your “Placeholder” oval, then you’ve got it right so far.

Next, back in createList.php, break up the code to add your PHP. At the top, add a simple multidimensional array for testing purposes. This is where you would normally do a database fetch or JSON call or some other bit of data wizardry. You can use the same snippet from your landing page:

$employees =
array('id'=>1, 'name'=>'Apollo', 'jobtitle'=>'God of Music'),
array('id'=>2, 'name'=>'Aphrodite', 'jobtitle'=>'Goddess of Love'),
array('id'=>3, 'name'=>'Mars', 'jobtitle'=>'God of War'),
array('id'=>4, 'name'=>'Artemis', 'jobtitle'=>'Goddess of the Hunt') );


Go down to your Grid container nesting the Ellipse and TextBlock. Since you’ve built a prototype object, you can wrap your PHP around that to iterate through your data collection. Here’s an example, with some slight tweaking to the Margin properties to adjust the spacing:

$n = 0;
foreach ($employees as $employee) {
echo('<Grid x:Name="' . $employee['jobtitle'] . '" HorizontalAlignment="Left" Height="80" Margin="' . (($n * 150) + ($n * 5) + 5) . ',23,0,0" VerticalAlignment="Top" Width="150" MouseLeftButtonDown="mouseClick">');
echo('<Ellipse Fill="#FF4F8DC8" Stroke="Black"/>');
echo('<TextBlock FontWeight="Bold" FontSize="13.333" FontFamily="Trebuchet MS" Margin="20,31,18,21" TextAlignment="Center" TextWrapping="Wrap" Text="' . $employee['name'] . '"/>');
$n ++;


Notice that this code snippet also includes your MouseLeftButtonDown event. This is the manual part of hooking up the Storyboard that you need to do by hand.

You might also notice a bit of a hack in this example: improper use of a Name property. This is used for demonstration purposes only and should not be attempted at home. In a real-life scenario, you might instead store the ID field in the name field and then incorporate some more complex data-fetching to populate additional fields.

One last piece of business to complete the hookup. Go back to your xamlFunctions.js file and add the following to the end:

function mouseClick(sender, mouseEventArgs)
sender.findName("bubbleText")["Text"] = sender.Name;


As you can see, this is a simple function to populate the text of your bubbleText grid, then start the bubbleOut Storyboard.

With that in place, reload PHPEmpList.php. If all went well, you should see a list of your “employees” across the top. Click on one to see your bouncy animation. (If all did not go well, here is the complete code listing for this project.)



You can see the code in action here:




If you have a PHP already built and ready to go, but it needs that little extra something, this is one easy way to Silverlight that PHP app. By using Expression Blend, you can build out your user interface and add some animation effects without writing a line of code. Then just steal the XAML and use that as the base for your front-end. With some JavaScript to hook up the animation, the final result is a RIA that has no real equivalent in the AJAX/DOM world.



Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}