Object Positioning in Silverlight

This overview demonstrates how to control the position of objects (such as shapes, text, and media) in your Microsoft Silverlight-based application.

The overview contains the following sections:

  • Plug-in Position and Dimensions
  • The Canvas Object
  • Positioning Paths, Geometries, and Other Shapes
  • Transforms
  • Z-Order

Plug-in Position and Dimensions

The Silverlight plug-in defines the area that the Silverlight-based application displays in. You embed the plug-in within its host HTML page and you can either position the plug-in somewhere inline in the HTML page display or you can have the plug-in take up the entire HTML page. Because of this, there are two frames of reference when positioning Silverlight objects.

  • Within the plug-in: Position objects relative to the root Canvas within the plug-in. Most of this overview describes this type of positioning.
  • Within the HTML: The entire plug-in and all the objects positioned within it are subject to where you place the plug-in in HTML.

Position of the plug-in within the HTML page depends on where you put the HTML container element (usually a DIV) within the HTML. In the example below, the HTML embeds the plug-in within an HTML TABLE.

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
    <title>Using CreateFromXaml Method</title>
    <script src="Silverlight.js" type="text/javascript"></script>
    <script src="CreateSilverlight.js" type="text/javascript"></script>
    <script type="text/javascript" src="position_inside_html1.js"></script>
    <style>
     html,body { height:100%; margin:0; padding:0;}
    </style> 
</head>
<body>
     <table>
       <tr>
         <td>Top Table Row</td>
       </tr>
       <tr>
         <td>
           <!-- This DIV contains the Silverlight plug-in. -->
           <div id="placeHolderElement">     
             <script type="text/javascript">  
                var placeHolderElement = document.getElementById("placeHolderElement");
                                       
                createSilverlight();        
              </script>  
          </div>
          </td>
        </tr>
       <tr>
         <td>Bottom Table Row</td>
       </tr>
    </table>
</body>
</html>

The following illustration shows the previous HTML, given a Silverlight-based application that contains only a red Canvas that is 50 pixels wide and 50 pixels high.

A plug-in instance inside an HTML page

A plug-in instance inside an HTML page

In the previous example, the plug-in displayed as 50 pixels high and 50 pixels wide. To specify dimensions like this, you need to keep in mind three different files where dimensions are typically set.

  • HTML file: The HTML file has to allow the plug-in to be displayed. For example, HTML objects can lay on top of the plug-in or crowd it out of display.

  • CreateSilverlight.js file: The function in the CreateSilverlight.js helper file can specify the size of the plug-in. For example, the following code shows how to specify dimensions of 50 pixels by 50 pixels within the Silverlight.createObject method defined inside the CreateSilverlight.js file.

  • Root Canvas: You can set width and height properties on the root Canvas of your application. The following code shows the 50-by-50 red Canvas.

If you are embedding a plug-in with specific dimensions you may have to make sure all three locations match.

Instead of embedding the plug-in within a larger HTML page, you might want to have the plug-in take up the entire Web page. In the following HTML, the width and height are set to 100% for the HTML element, BODY element, and the DIV that contains the plug-in.

HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" >
<head>
  <title>My Silverlight Application</title>
  <!-- Helper files for initializing and creating the Silverlight plug-in -->
  <script type="text/javascript" src="Silverlight.js"></script>
  <script type="text/javascript" src="CreateSilverlight.js"></script>
  
    <style>
     html,body { height:100%; margin:0; padding:0;}
    </style> 
 
 </head>
<body>
  <div id="slPluginHost" style="width:100%;height:100%" >
    <script type="text/javascript">
      // Create a variable that references the HTML element that hosts the plug-in.
      var parentElement = document.getElementById("slPluginHost");
      
      // Initialize and create the plug-in.
      createSilverlight();
    </script>
  </div>
</body>
</html>

In addition to setting the height and width to 100% in the HTML page, set the height and width to 100% in the CreateSilverlight.js file, as follows.

JavaScript
function createSilverlight()
{  
    Silverlight.createObject(
        "position_inside_html2.xaml",       // Source property value.
        parentElement,                      // DOM reference to hosting DIV tag.
        "myPlugin",                         // Unique plug-in ID value.
        {                                   // Plug-in properties.
            width:'100%',                   // Width of rectangular region of plug-in.
            height:'100%',                  // Height of rectangular region of plug-in.
            inplaceInstallPrompt:false,     // Determines whether to display in-place install prompt if invalid version is detected.
            background:'white',             // Background color of plug-in.
            isWindowless:'false',           // Determines whether to display plug-in in windowless mode.
            framerate:'24',                 // MaxFrameRate property value.
            version:'1.0'                   // Silverlight version.
        },
        {
            onError:null,                   // OnError property value -- event-handler function name.
            onLoad:null                     // OnLoad property value -- event-handler function name.
        },
        null,                               // initParams -- user-settable string for information passing.
        null);                              // Context value -- passed to Silverlight.js onLoad event handlers.
}

The Canvas Object

All Silverlight objects must be contained in a Canvas object and positioned relative to their containing Canvas. You control the positioning of objects inside the Canvas by specifying x and y coordinates. These coordinates are in pixels, which are resolution-independent. The x and y coordinates are often specified by using the Canvas.Left and Canvas.Top attached properties. Canvas.Left specifies the object's distance from the left side of the containing Canvas (x coordinate), and Canvas.Top specifies the object's distance from the top of the containing Canvas (y coordinate).

The following example shows how to position a rectangle 30 pixels from the left and 30 pixels from the top of a Canvas.

XAML
<Canvas
	xmlns="https://schemas.microsoft.com/client/2007"
	xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
	Width="640" Height="480"
	Background="White"
	>
	<Rectangle Canvas.Left="30" Canvas.Top="30" Fill="red" 
	Width="200" Height="200" />
</Canvas>

The following illustration shows how this code renders inside the Canvas.

Positioning a rectangle inside the Canvas

Positioning a rectangle inside the Canvas

Note   Silverlight does not support high dpi in version 1. Therefore, objects rendered on the screen and the coordinate system do not scale in response to monitor resolution. In addition, coordinates that are used by mouse events are not affected by monitor resolution.

You can nest Canvas objects and position them by using the Canvas.Left and Canvas.Top properties. When you nest objects, the coordinates used by each object are relative to its immediate containing Canvas. In the following example, the root (white) Canvas contains a nested (blue) Canvas that has Canvas.Left and Canvas.Top properties of 30. The nested blue Canvas contains a red rectangle that also has Canvas.Left and Canvas.Top values of 30.

XAML
<Canvas
	xmlns="https://schemas.microsoft.com/client/2007"
	xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
	Width="300" Height="300"
	Background="White">
	
    <Canvas Width="250" Height="250" Canvas.Left="30" Canvas.Top="30"
	Background="blue">
	
	  <Rectangle Canvas.Left="30" Canvas.Top="30" Fill="red" 
	  Width="200" Height="200" />
	  
    </Canvas>
	
</Canvas>

The following illustration shows how this code renders.

Nested objects

Nested objects

Note   In Silverlight-based applications that are embedded in HTML pages, the HTML element that hosts the Silverlight plug-in often has a specific width and height. Because of this, it is possible for objects to be positioned out of view. For example, if your host HTML element is only 300 pixels wide and you position an object 400 pixels to the right in your Silverlight-based application, your users will not be able to see the object.

Positioning Paths, Geometries, and Other Shapes

Not all objects are positioned by using the Canvas.Left and Canvas.Top properties. However, they all use x and y coordinates that are relative to the containing Canvas. Examples of these objects include the Path object, various geometry objects, and shapes such as Line. The following example shows the positioning syntax for some of these objects. For more information about paths, geometries, and other shapes, see Shapes and Drawing in Silverlight Overview, Geometries Overview, and Path Markup Syntax.

XAML
<Canvas
	xmlns="https://schemas.microsoft.com/client/2007"
	xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
	Width="300" Height="300"
	Background="White">
  
  <!-- Simple line gives X and Y coordinates for the start
       and end of the line. -->
  <Line X1="280" Y1="10" X2="10" Y2="280"
      Stroke="Blue" StrokeThickness="5"/>
  <!-- A Polyline allows you to specify a number of X,Y coordinates
       to make a series of connected lines -->
  <Polyline Points="150, 150 150, 250 250, 250 250, 150"
      Stroke="Yellow" StrokeThickness="10"/>
  <!-- Path allows you to create more complex shapes including curves.
       Again, the shape of the Path is specified by coordinates. -->
  <Path Data="M 10,100 C 10,300 300,-200 250,100z"
      Stroke="Red" Fill="Orange"
      Canvas.Left="10" Canvas.Top="10" />
	
</Canvas>

The following illustration shows how this code renders.

Positioning Line, Polyline, and Path objects

Positioning Line, Polyline, and Path objects

Transforms

Another way to change the position of an object is to apply a transform to it. You can use transforms to move the object, rotate the object, skew the object's shape, change the size (scale) of the object, or a combination of these actions.

The following example shows a RotateTransform that rotates a Rectangle element 45 degrees about the point (0,0).

XAML
<Canvas
  xmlns="https://schemas.microsoft.com/client/2007"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  Width="200" Height="200">
  <Rectangle
    Canvas.Left="100" Canvas.Top="100"
    Width="50" Height="50"
    Fill="RoyalBlue">
    <Rectangle.RenderTransform>
      <RotateTransform Angle="45" />
    </Rectangle.RenderTransform>
  </Rectangle>
</Canvas>

The following illustration shows how this code is rendered.

A Rectangle rotated 45 degrees about the point (0,0)

A Rectangle rotated 45 degrees about (0,0)

For more information about transforms and how to use them, see Transforms Overview.

Z-Order

So far, the discussion has focused on positioning objects in two-dimensional space. You can also position objects on top of one another. The z-order of an object determines whether an object is in front of or behind another overlapping object. By default, the z-order of objects within a Canvas is determined by the sequence in which they are declared. Objects that are declared later appear in front of objects that are declared first. The following example creates three Ellipse objects. You can see that the Ellipse declared last (the lime-colored ellipse) is in the foreground, in front of the other two Ellipse objects.

XAML
<Canvas
    xmlns="https://schemas.microsoft.com/client/2007"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">
  
  <Ellipse 
      Canvas.Left="5" Canvas.Top="5" 
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Silver" />
      
  <Ellipse 
      Canvas.Left="50" Canvas.Top="50" 
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="DeepSkyBlue" />      
      
  <Ellipse 
      Canvas.Left="95" Canvas.Top="95" 
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Lime" />     
              
</Canvas>

The following illustration shows how this code renders.

Overlapping Ellipse objects

Overlapping Ellipse objects

You can change this behavior by setting the Canvas.ZIndex attached property on objects within the Canvas. Higher values are closer to the foreground; lower values are farther from the foreground. The following example is similar to the preceding one, except that the z-order of the Ellipse objects is reversed. The Ellipse that is declared first (the silver ellipse) is now in front.

XAML
<Canvas
    xmlns="https://schemas.microsoft.com/client/2007"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">
  
  <Ellipse 
      Canvas.ZIndex="3"
      Canvas.Left="5" Canvas.Top="5" 
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Silver" />
      
  <Ellipse 
      Canvas.ZIndex="2"
      Canvas.Left="50" Canvas.Top="50" 
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="DeepSkyBlue" />      
      
  <Ellipse 
      Canvas.ZIndex="1"
      Canvas.Left="95" Canvas.Top="95" 
      Height="200" Width="200"
      Stroke="Black" StrokeThickness="10" Fill="Lime" />     
              
</Canvas>

The following illustration shows how this code renders.

Reversing the z-order of the Ellipse objects

Reversing the z-order of the Ellipse objects

See Also

Shapes and Drawing Overview
Geometries Overview
Path Markup Syntax
Transforms Overview
Silverlight Object Models and Scripting to the Silverlight Plug-inbr />Overviews and How-to Topics