Build a Basic Example
All HTML files that host Silverlight controls have a few common characteristics that you'll need to include those in your code. First, you need to include a
<script> reference to
Silverlight.js. Next, you need to have a named HTML element such as a
<div> that has an
id attribute. That's the ID you'll use to initialize the Silverlight XAML. Finally, you need to define a JavaScript function that initializes your Silverlight control; in the following example that function is called
createMySilverlightControl():
<html>
<head>
<title>Silverlight Test</html>
<script type="text/javascript" src="Silverlight.js"></script>
<script language="javascript">
function createMySilverlightControl()
{
Sys.Silverlight.createObject(
"Simple.xaml", // Your XAML object.
// DOM reference to hosting DIV tag.
document.getElementById("Holder"),
"SimpleEllipse", // Unique control ID value.
{
width:'100',
height:'40',
//If true, will prompt user to install
// if they don't have Silverlight.
inplaceInstallPrompt:true,
background:'#FFFFFFFF', // ARGB Background color of control.
isWindowless:'false', //False, opaque bg
framerate:'24', // MaxFrameRate property value.
version:'0.9' // Control version to use.
},
{
onError:null,//JS method to call on error
onLoad:null//JS method to call on load
},
null);// Parameters
}
</script>
</head>
<body>
<div id="Holder"></div>
<script type="text/javascript">
createMySilverlightControl();
</script>
</body></html>
In your
createMySilverlightControl function, call
Sys.Silverlight.createObject(), which accepts parameters that define what XAML file to use, some properties specifying where and how you want your Silverlight application to run, and any custom parameters you want to pass in to it. The
Simple.html file shown above references the
Simple.xaml file shown below:
<Canvas Width="100" Height="40"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 | |
Figure 1. Simple Ellipse: Here's a simple ellipse drawn by Silverlight in Firefox. |
<Ellipse Width="100" Height="40"
Stroke="Black" StrokeThickness="2"
Fill="Green" />
</Canvas>
Together, these two XAML and HTML files provide a minimal example of a Silverlight application. This simple demo doesn't do much—but it does display the green ellipse shown in
Figure 1.
The XAML code creates a 100 x 40-pixel Canvas control containing a green ellipse with a black border. It has no defined interactivity; in other words, clicking on it or mousing over it doesn't do anything. For a primer on how XAML is structured, take a look at the article
Developing Lookless controls with WPF. For a list of elements supported in Silverlight—a fairly small subset of those supported in WPF—take a look at the
Silverlight 1.0 reference.