Understanding Your Hosting Options
Silverlight exposes a number of properties and events that customize the appearance of the Silverlight content and the way it interacts with the HTML document it lives inside. In addition, the source parameter exposed by the Silverlight add-on supports more functionality than previously described. This section examines the extra functionality of source, and then looks at all the properties and events that the add-on directly exposes.
source
Previous listings have demonstrated the most common usage of source setting it to the name (and path, if applicable) of a XAML file on the web server. However, you can alternatively place your XAML inline in the HTML document. There are two steps for doing this:
- Place your XAML content within a SCRIPT element with type text/xaml somewhere in the document before the HTML element that will contain the Silverlight control, and give it a unique id.
- Use the SCRIPT element's id preceded by a # as the source value given to the Silverlight add-on. The # prefix is what distinguishes an id from a filename.
Listings 1.6 and 1.7 are updates to Listings 1.4 and 1.5 that remove the dependency on the separate Chapter1.xaml file.
Listing 1.6. Placing Inline XAML Inside HTML
<html> <head> <title>Great Estates</title> <script type="text/javascript" src="Silverlight.js"></script> <script type="text/javascript" src="CreateSilverlight.js"></script> </head> <body style="background:blue"> <!-- A Silverlight-based logo: --> <script id="xaml" type="text/xaml"> <Canvas xmlns="http://schemas.microsoft.com/client/2007"> <MediaElement Name="video" Source="Lake.wmv" Opacity="0" IsMuted="true"/> <!-- A circle containing a live video: --> <Ellipse Width="100" Height="100"> <Ellipse.Fill> <VideoBrush SourceName="video"/> </Ellipse.Fill> </Ellipse> <!-- Two pieces of text: --> <TextBlock FontFamily="Georgia" Foreground="Blue" FontStyle="Italic" FontSize="40" Canvas.Left="125" Canvas.Top="20" Text="Great Estates"/> <TextBlock Foreground="Blue" Canvas.Left="110" Canvas.Top="70" Text="Luxurious Living at an Affordable Price"/> <!-- Curves and a line: --> <Path Stroke="Red" StrokeThickness="4"> <Path.Data> <PathGeometry> <PathFigure StartPoint="0,65"> <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="25,65"/> <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="50,65"/> <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="75,65"/> <ArcSegment SweepDirection="Clockwise" Size="2,2" Point="100,65"/> <LineSegment Point="390,65"/> </PathFigure> </PathGeometry> </Path.Data> </Path> </Canvas> </script> <div id="placeholder"> <script type="text/javascript">createSilverlight();</script> </div> <p style="font-family:Tahoma; color:white"> An idyllic new community located high on a hill and offering captivating waterfront views. Tailored to meet both the needs of upsizing and downsizing buyers, Great Estates offers custom quality architecture and design at an affordable price point. </p> </body> </html>
Listing 1.7. CreateSilverlight.js—Using Inline XAML as the source
function createSilverlight() { Silverlight.createObjectEx( { source: "#xaml", parentElement: document.getElementById("placeholder"), id: "silverlightControl", properties: { width: "390", height: "100", version: "1.0", background: "Yellow" }, events: {} } ); }
This #id syntax is supported anywhere the source might be specified: createObject, createObjectEx, directly on an EMBED element, or as a PARAM inside an OBJECT element. This functionality is a handy way to combine what would ordinarily be two web requests into one. But in addition to efficiency considerations, removing the dependency on a custom external file enables server-side code (in technologies such as ASP.NET or PHP) to emit Silverlight content in a completely encapsulated way.
Properties
The width, height, and version properties exposed by Silverlight are straightforward, but the background property could use a little more explanation. In addition, the Silverlight add-on supports more properties that haven't been discussed yet.
background
The background property—which can be set via createObject, createObjectEx, or directly on an OBJECT/EMBED element—is more powerful than a normal HTML color value. Besides named colors—such as Red or Yellow—and RGB values—such as #F1F1F1 or #456, background can be given an alpha channel for creating transparent or translucent background colors. The syntax is #AARRGGBB (or #ARGB), so a translucent red color would be #77FF0000 (or #7F00). background can also be set to the named value Transparent, which is the same as any color with an alpha channel value of zero. If you omit background altogether, the control will be given a white background.
isWindowless
By default, an instance of the Silverlight control is known as windowed, but by setting isWindowless to true (which can be done via createObject, createObjectEx, or directly on an OBJECT/EMBED element), you can change it to be a windowless control. The distinction of windowed versus windowless isn't specific to Silverlight, but rather refers to a low-level implementation detail on Windows (whether the control has its own window handle, or HWND).
The important thing to understand is the two different behaviors of a windowless control:
- A windowless control respects HTML z-indexing, so you can overlay and overlap HTML content on top of Silverlight and vice versa. A windowed control, on the other hand, is always rendered on top.
- A windowless control supports transparency, so it can be given a transparent or translucent background, and content inside it can be transparent or translucent.
Figure 1.5 shows a potential way that the Great Estates website might take advantage of windowless Silverlight content—placing an HTML SELECT element on top of the Silverlight logo.
Figure 1.5 A windowless Silverlight control allows HTML to appear on top of it.
To create the result in Figure 1.5, Listing 1.8 adds a SELECT element to the page from Listing 1.4 and uses CSS to give it an absolute position and a z-index to ensure that it is placed on top of the Silverlight content.
Listing 1.8. Placing an HTML SELECT Element in Front of the Silverlight Control
<html> <head> <title>Great Estates</title> <script type="text/javascript" src="Silverlight.js"></script> <script type="text/javascript" src="CreateSilverlight.js"></script> </head> <body style="background:blue"> <!-- A Silverlight-based logo: --> <div id="placeholder"> <script type="text/javascript">createSilverlight();</script> </div> <select style="position:absolute; left:289px; top:18px; z-index:1"> <option>California</option> <option>Pennsylvania</option> <option>Washington</option> </select> <p style="font-family:Tahoma; color:white"> An idyllic new community located high on a hill and offering captivating waterfront views. Tailored to meet both the needs of upsizing and downsizing buyers, Great Estates offers custom quality architecture and design at an affordable price point. </p> </body> </html>
Listing 1.8 only produces the desired result because the corresponding CreateSilverlight.js file sets isWindowless to true, as shown in Listing 1.9.
Listing 1.9. CreateSilverlight.js—Hosting Familiar Silverlight Content in a Windowless Control
function createSilverlight() { Silverlight.createObjectEx( { source: "Chapter1.xaml", parentElement: document.getElementById("placeholder"), id: "silverlightControl", properties: { width: "390", height: "100", version: "1.0", background: "Yellow", isWindowless: "true" }, events: {} } ); }
inplaceInstallPrompt
The inplaceInstallPrompt property, which can only be used with createObject or createObjectEx, controls the look and behavior of the Silverlight installation graphic that gets displayed when the viewer doesn't have the appropriate version of Silverlight. Figure 1.6 shows the appearance of the two options. Setting inplaceInstallPrompt to false (the default behavior) gives a small graphic that links to the official download page with more information. Setting it to true gives additional text, but the link now points directly to the file to download rather than an intermediate page.
Figure 1.6 The two different install prompts supported by Silverlight.js.
maxFramerate
The maxFramerate parameter, which can be set via createObject, createObjectEx, or directly on an OBJECT/EMBED element, customizes the maximum frame rate that the Silverlight control renders content, measured in frames per second. (The actual frame rate is dependent on the client computer and its current load.) The default value for maxFramerate is 24. If you decide to customize maxFramerate, you should select the lowest number possible that gives you the results you need.
The frame rate controls all content inside the Silverlight control—animations and even video—except for audio. You can see this with the Great Estates logo by setting its maxFramerate to 1 and changing IsMuted to false instead of true in the XAML file. This causes the video to progress in an extremely choppy fashion, yet the corresponding audio plays smoothly.
Events
The Silverlight control supports two events that can be set directly on the OBJECT or EMBED element: onLoad and onError. You can assign either event the name of a JavaScript function to be called. For example:
<object type="application/x-silverlight" id="silverlightControl" width="390" height="100"> <param name="background" value="Yellow"/> <param name="source" value="Chapter1.xaml"/> <param name="onLoad" value="myFunction"/> </object>
However, because handling either of these events requires the use of JavaScript, you might as well take advantage of createObject or createObjectEx rather than attaching these handlers the "raw" way.
onLoad
The onLoad event is raised as soon as the XAML content has been loaded. Handling this event is useful for performing custom initialization of Silverlight content, such as initiating animations or dynamic positioning/sizing of the control based on document dimensions. These specific kinds of activities are covered in later chapters, but Listing 1.10 at least demonstrates how to designate a function as a handler for the onLoad event.
Listing 1.10. CreateSilverlight.js—Assigning an onLoad Handler
function createSilverlight() { Silverlight.createObjectEx( { source: "Chapter1.xaml", parentElement: document.getElementById("placeholder"), id: "silverlightControl", properties: { width: "390", height: "100", version: "1.0", background: "Yellow" }, events: { onLoad: myFunction } } ); } function myFunction(control, context, rootElement) { // Perform custom initialization }
The purpose of Silverlight's onLoad event is similar to the HTML DOM's onload event. However, to avoid timing issues, you should stick to the HTML onload event for manipulating HTML content and Silverlight's onLoad event for manipulating Silverlight content.
Handlers for the onLoad event are passed three parameters:
- control, which is the instance of the Silverlight control. The next section, "Interacting with the Silverlight Control Programmatically," describes some of the things you can do with this object.
- context, which is simply whatever custom context value was given to createObject or createObjectEx (if one was given).
- rootElement, which is the instance of the root element in the source XAML content. The next chapter explains how you can programmatically interact with Silverlight elements declared in XAML.
onError
The onError event is raised whenever Silverlight throws an exception not already handled by your JavaScript code. (For an exception thrown from a synchronous function call, this means that no corresponding try/catch block exists. For an exception thrown from an asynchronous function call, this means that no event handler is attached for that specific failure case.) Exceptions can be raised by Silverlight for XAML parsing errors or for any number of runtime errors.
If you don't specify a handler for onError when directly using an OBJECT or EMBED element, unhandled Silverlight errors are swallowed. But when you use createObject or createObjectEx, a function called default_error_handler is automatically set as the handler for onError unless you provide your own. The default handler calls JavaScript's alert function to display a simple dialog, such as the one shown in Figure 1.7.
Figure 1.7 When good content goes bad.
To understand how to create your own onError handler, it is instructive to look at the implementation of default_error_handler inside Silverlight.js. It is effectively implemented as follows:
function default_error_handler(sender, args) { var errMsg = "\nSilverlight error message\n"; // All errors have a numeric code, a type, and a message errMsg += "ErrorCode: " + args.errorCode + "\n"; errMsg += "ErrorType: " + args.errorType + "\n"; errMsg += "Message: " + args.errorMessage + "\n"; if (args.errorType == "ParserError") { // A parser error gives the location in the XAML content errMsg += "XamlFile: " + args.xamlFile + "\n"; errMsg += "Line: " + args.lineNumber + "\n"; errMsg += "Position: " + args.charPosition + "\n"; } else if (args.errorType == "RuntimeError") { if (args.lineNumber != 0) { // Display the line number and character, if the information exists errMsg += "Line: " + args.lineNumber + "\n"; errMsg += "Position: " + args.charPosition + "\n"; } // The name of the function that failed errMsg += "MethodName: " + args.methodName + "\n"; } // Display the message in a simple alert box: alert(errMsg); }
The sender is the object on which the error occurred, if applicable. For parser errors, such as the one shown in Figure 1.6, sender is null. The args object provides a number of pieces of information that depend on the type of error raised, as seen in the implementation of default_error_handler.