Silverlight SDK

[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

Referencing and Modifying Silverlight Objects

You can access and modify objects in your Silverlight application at run time. For objects that are part of a collection, or child objects, you can use the methods of the Collection object to reference and modify object values.

This topic contains the following section:

Referencing Objects

You can reference objects in the Silverlight object hierarchy using methods of the Document Object Model (DOM) and Silverlight object model.

Referencing the Silverlight Control

You can retrieve the Silverlight control value by using the GetHost function from any UIElement-derived object. This function is useful in event handler functions, in which the sender parameter is passed. The following JavaScript example shows how to retrieve the Silverlight control by using the GetHost function:

JavaScript
function onKeyUp(sender, keyEventArgs)
{
    // Determine whether the keystroke combination CTRL+V was detected.
    if ((keyEventArgs.key == 51) && (keyEventArgs.ctrl == true))
    {
        // Retrieve a reference to the control.
        var control = sender.getHost();

        // Display the current version of the control.
        alert("Silverlight version: " + control.settings.version);
    }
}

For more information on accessing Silverlight controls, see Using Silverlight Controls.

Finding a XAML Object

You can find any object in the Silverlight object hierarchy by using the findName method and referencing the object's x:Name attribute value. This means that the object you are searching for does not have to be a direct descendant of the object that invokes the  findName method. If the method is successful, a reference to the object is returned; otherwise, null is returned. The following JavaScript example shows how a leaf node of a Silverlight object hierarchy can access a root node.

JavaScript
// Loaded event handler for the root Canvas object.
function onLoaded(sender, eventArgs)
{
    // Retrieve the object corresponding to the x:Name attribute value.
    var canvas = sender.findName("rootCanvas");

    // Determine whether the object was found.
    if (canvas != null)
    {
        alert(canvas.toString());
    }
    else
    {
        alert("Object not found");
    }
}

Referencing an Object in a Collection

You can retrieve a specific child of a parent object by referencing the index of the collection of the parent object. The following JavaScript example shows how to retrieve a child of a parent Canvas object by using the GetItem method:

JavaScript
function getObject(parent, index)
{
    // Determine if the index is valid.
    if (index < parent.children.count)
    {
        // Retrieve the child object at the specified index in the collection.
        var object = parent.children.getItem(index);
    }

    return object;
}

Enumerating Child Objects

You can enumerate the child of a parent object by accessing the children collection of the parent object. The following JavaScript example shows how to enumerate the children of a parent Canvas object:

JavaScript
function getChildren(parent, index)
{
    // Enumerate the children of the Canvas object.
    for (i = 0; i < parent.children.count; i++)
    {
        var child = parent.children.getItem(i);

        // Display the index and type of the child object.
        alert(i + ": " + child.toString());
    }
}

Referencing Object Properties

You can reference object properties at run time by using the GetValue and SetValue methods.

Using the GetValue Method

You can use the GetValue method to get the value of a property. You can also use the abridged "." (dot) notation as an equivalent syntax of the GetValue method. The following JavaScript example shows to get a property value by using both the GetValue method and abridged "." (dot) notation:

JavaScript
function onMouseLeftButtonUp(sender, index)
{
    // Get the property value using the GetValue method.
    var opacity = sender.getValue("opacity");

    // Get the property value using the equivalent "." notation.
    var opacity = sender.opacity;

    alert("Opacity = " + opacity);
}

Using the SetValue Method

You can use the SetValue method to set the value of a property. You can also use the abridged "." (dot) notation as an equivalent syntax of the SetValue method. The following JavaScript example shows to set a property value by using both the SetValue method and abridged "." (dot) notation:

JavaScript
function onMouseEnter(sender, index)
{
    // Set the property value using the SetValue method.
    sender.setValue("opacity", 0.5);

    // Set the property value using the equivalent "." notation.
    sender.opacity = 0.5;
}

For properties that are attached properties, such as Canvas.Top, you must use the abridged "." (dot) notation syntax in a slightly different way:

JavaScript
// Set the property value using the SetValue method.
sender.setValue("Canvas.Top", 40);

// Set the property value using the equivalent "." notation.
sender["Canvas.Top"] = 40;

Adding Objects

You can add XAML content to objects that support child objects, such as the Canvas object. The following JavaScript example shows to create a TextBlock and add it to the root Canvas object by using the Add method on the object's collection of children. Note that the Opacity property is 0, so the fragment will not be initially visible. Using the Opacity property to control an object's visibility avoids having to modify the Silverlight object hierarchy.

JavaScript
var textBlock;

function onLoaded(sender, eventArgs)
{
    // Retrieve the id of the control.
    var control = sender.getHost();

    // Define and create a XAML fragment.
    var xamlFragment = '<TextBlock Canvas.Top="200" Opacity=".5" Text="Click for more info" />';
    textBlock = control.content.createFromXaml(xamlFragment);

    // Add the TextBlock to the root Canvas object.
    sender.children.add(textBlock);
}

// Toggle the Opacity property for the TextBlock.
function onToggle()
{
    if (textBlock.opacity)
    {
        textBlock.opacity = 0;
    }
    else
    {
        textBlock.opacity = 1;
    }
}

How Adding Objects Affects Z-Order

When you use the Add method, you add the object to the end of the parent object's collection. Since sibling objects are rendered starting from the first object to the last object, an object added to the end of a collection is displayed on top of all of its sibling objects. The following JavaScript example shows three objects added to a collection:

JavaScript
// Add three overlapping Rectangle objects.
function AddItems(rootCanvas)
{
    var control = rootCanvas.getHost();

    var xamlFragment = '<Rectangle Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />';
    var rectangle_1 = control.content.createFromXaml(xamlFragment);
    rootCanvas.children.add(rectangle_1);

    var xamlFragment = '<Rectangle Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />';
    var rectangle_2 = control.content.createFromXaml(xamlFragment);
    rootCanvas.children.add(rectangle_2);

    var xamlFragment = '<Rectangle Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />';
    var rectangle_3 = control.content.createFromXaml(xamlFragment);
    rootCanvas.children.add(rectangle_3);
}

Here is the display result of the previous JavaScript example. Notice that when you add objects to a collection, the most recent object added is higher in the z-order. In this case, the third rectangle is displayed on top of the two other rectangles. Notice the index value of each new object as it is added to the collection:
 


Z-order of added objects to the collection


Inserting an Object into a Collection

When you use the Insert method, you add the object to a specified index in the parent object's collection. Existing objects are shifted to make room for the new inserted object. The following JavaScript example shows an object inserted into the beginning of a collection.

JavaScript
// Insert an overlapping Rectangle object.
function InsertItem(rootCanvas)
{
    var control = rootCanvas.getHost();

    var xamlFragment = '<Rectangle Fill="Black" Canvas.Top="0" Canvas.Left="0" Height="100" Width="100" />';
    var rectangle_4 = control.content.createFromXaml(xamlFragment);
    rootCanvas.children.insert(0, rectangle_4);
}

Here is the display result of the previous JavaScript example.  Notice that the rendering of the inserted object. Since the inserted object is the first object in the collection, it is overlaid by all of its siblings:
 

Z-order of an inserted object into the collection

Removing Objects

You can remove objects from the Silverlight object hierarchy by using the Remove and RemoveAt methods. As soon as objects are removed from the Silverlight object hierarchy, they are no longer rendered. When you remove an object using the Remove or RemoveAt methods, you are disconnecting the object from the Silverlight object hierarchy. The disconnected object is now a XAML fragment that can be connected back to the object hierarchy using the Add method. The following two diagrams illustrate the process of disconnecting objects from the Silverlight object hierarchy:

Removing objects from the Silverlight object hierarchy
Removing an object from the Silverlight object hierachy


Disconnected XAML fragment and Silverlight object hierarchy
Disconnected XAML fragment and Silverlight object hierarchy


The following JavaScript example shows to remove a TextBlock from its parent Canvas object by using the Remove method on the object's collection of children.

JavaScript
function removeCaption(rootCanvas)
{
    // Retrieve the TextBlock object.
    var captionTextBlock = rootCanvas.findName("myCaption");

    if (captionTextBlock != null)
    {
        rootCanvas.children.remove(captionTextBlock);
    }
}

The RemoveAt method allows you to remove a child object at a specified index value in the parent's collection. This means the child object does not require an x:Name attribute value The following JavaScript example shows to remove the first object from a parent Canvas object by using the RemoveAt method:

JavaScript
// Remove the first child object from the parent collection.
myCanvas.children.removeAt(0);

Removing All Objects from a Collection

You can remove all objects in a collection by using the Clear method, which is equivalent to using the RemoveAt method for each item in the collection. The following JavaScript example shows to removes all items from a collection using the Clear method.

JavaScript
// Remove all child objects from the parent collection.
myCanvas.children.clear();

Changing the Z-Order of Objects

The Canvas.ZIndex property value represents the z-order rendering behavior of objects in a collection. The following XAML example shows how to define two sets of Rectangle objects. The second set of rectangles sets the Canvas.ZIndex property to invert the z-order:

XAML
<!-- Render rectangles using default z-order (position within the collection). -->
<Canvas>
  <Rectangle
    Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />
  <Rectangle
    Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />
  <Rectangle
    Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />
</Canvas>

<!-- Render rectangles using explicit z-order by using Canvas.ZIndex. -->
<Canvas Canvas.Left="200">
  <Rectangle
    Canvas.ZIndex="2"
    Fill="Maroon" Canvas.Top="20" Canvas.Left="20" Height="100" Width="100" />
  <Rectangle
    Canvas.ZIndex="1"
    Fill="LightBlue" Canvas.Top="40" Canvas.Left="40" Height="100" Width="100" />
  <Rectangle
    Canvas.ZIndex="0"
    Fill="Teal" Canvas.Top="60" Canvas.Left="60" Height="100" Width="100" />
</Canvas>

The following image displays the result of the previous XAML content example:


Changing the z-order of objects within a collection

The first set of Rectangle objects uses the default z-order rendering of objects, which is based on the position of the child object in the Canvas collection--the first object in the collection is rendered first, then the second object, and so forth. The second set of Rectangle objects uses the Canvas.ZIndex property to override the default z-ordering of objects in the collection.

In the second set of Rectangle objects, the first object (the Maroon-colored one) is the highest in the z-order, or closest to the foreground. Its Canvas.ZIndex value is "2"--a purely arbitrary value. What is more important is that the value must be greater than any other child object Canvas.ZIndex value in the Canvas collection. If you do not explicitly set the Canvas.ZIndex value, it defaults to 0.

You can also set the Canvas.ZIndex value to a negative value, such as "-99", which places the object even farther from the foreground. Canvas.ZIndex values are aligned along the z-axis -- higher values are closer to the foreground; lower values are farther from the foreground. The following diagram shows the relationship of z-order to z-axis.


Relationship of z-order to z-axis

See Also

Using Silverlight Controls, Silverlight Events