Partilhar via


Collection

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

Represents a collection of objects.

Syntax Notes

See Derived Objects for syntax information.

Managed Equivalent

The managed API uses multiple collection types. The most common one used in Silverlight programming, at least for UI-specific tasks, is PresentationFrameworkCollection<T>.

Remarks

The Collection object is abstract. To use a collection in JavaScript, you must use one of the following derived collection types:

To obtain a collection in Silverlight, you get certain property values that reference the object that represents the collection. In some cases, these property values are read-only. A read-only collection property implies that the object that owns the collection defines the collection when it is created. You cannot replace that collection with a new collection object, but you can adjust the collection contents. To adjust the collection contents, get the collection property value, use it as an object reference, and call Collection methods on it.

For collection properties that are read/write, you can replace the collection. For example, if you use the CreateFromXaml method, and you want to replace all the items in an existing collection, you can declare the collection as the root element for the XAML you submit to CreateFromXaml. You can then set the collection property to the CreateFromXaml return value.

You can access the child objects of a parent object (the object that holds the relevant collection property) by using the methods of the Collection object. The most common collection used for this purpose is the VisualCollection that is the value of the Children (Panel) property.

Classes derived from Collection also have access to the methods of DependencyObject and can have a declared Name property in XAML.

Example

The following JavaScript example shows how to retrieve the collection of an object and access the members of the collection.

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());
    }
}