Share via


Add

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Adds an object to the end of the collection.

retval = object.Add(value)

Arguments

value

object

The object to add to the collection.

Return Value

Type: integer

The zero-based index of the inserted object in the collection, if successful; otherwise, null.

Managed Equivalent

Each collection type potentially implements this differently.

Remarks

Certain collections place importance on the collection order. For example, transforms in a TransformCollection object are applied in collection order, and child objects in the VisualCollection object for the Canvas.Children property are rendered in collection order (each object potentially rendering on top of previous objects). For these collections, you might want to use the Insert method to add a new item at a specific index. In other collections, such as the GradientStopCollection object, behavior is controlled by specific properties on objects in the collection, and the collection order is unimportant.

Example

The following JavaScript example shows how you can add XAML content to objects, such as the Canvas object, that support child objects. The example shows how to create a TextBlock object 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 visible initially. Using the Opacity property to control an object's visibility avoids the need to modify the Silverlight object hierarchy.

var textBlock;

function onLoaded(sender, eventArgs)
{
    // Retrieve the ID of the plug-in.
    var plugin = sender.getHost();

    // Define and create a XAML fragment.
    var xamlFragment = '<TextBlock Canvas.Top="200" Opacity=".5" Text="Click for more info" />';
    textBlock = plugin.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;
    }
}

See Also

Reference