Using Inline XAML


Instead of setting the initial Silverlight content by using a discrete file or package that is referenced by a Uniform Resource Identifier (URI), you can specify an area of inline HTML content that contains your XAML.

Important note Important Note:

Inline XAML is a concept that is only usable with the JavaScript API for Silverlight. Inline XAML is not compatible with the managed API for Silverlight.

Because of its relationship with the browser DOM, inline XAML constitutes a deliberate choice to use the JavaScript API. Without a discrete XAML file that is known to a managed project file, which specifies x:Class at its root, there is no way for an inline XAML solution to know how to connect the code-behind and XAML, and no specific instruction to compile and connect the managed code.

To use inline XAML, you must enclose the XAML in a special <SCRIPT> block and specify "text/xaml" as the type attribute. The XML document type declaration, <?xml version="1.0"?>, precedes the XAML content. The XAML content must be uniquely identified so that it can be referenced by the Source initialization parameter of the Silverlight plug-in. The source parameter uses the prefix "#" followed by the id value in the <SCRIPT> element to identify the XAML content. The XAML content can also define events that reference event handlers on the HTML page.

The following HTML example shows how to create inline XAML content. In this case, the HTML page contains both JavaScript and XAML content. Note the object element construction that specifies the source parameter.

Note Note:

The <SCRIPT> element that contains the inline XAML content must precede the HTML element that contains the Silverlight plug-in, which references the inline XAML for its source initialization.

  <title>Display Date</title>
  <!-- Define Loaded event handler for TextBlock. -->
  <script type="text/javascript">
    function setDate(sender, eventArgs)
      sender.text = Date();

<body bgcolor="Teal">

<!-- Define XAML content. -->
<script type="text/xaml" id="xamlContent"><?xml version="1.0"?>
      Loaded="setDate" />

<div id="silverlightControlHost">
  <object type="application/x-silverlight" width="100%" height="100%" id="slc">
    <param name="source" value="#xamlContent"/>
    <param name="onload" value="onLoaded" />
    <param name="iswindowless" value="true" />
  <iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>

When this page is displayed, the Silverlight plug-in is loaded and the Loaded event for the TextBlock object is raised, which causes the TextBlock to display the current date and time.

Community Additions