Compartir a través de


ItemContainerGenerator.ContainerFromIndex Method

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

Returns the container for the item at the specified index within the ItemCollection.

Namespace:  System.Windows.Controls
Assembly:  System.Windows (in System.Windows.dll)

Syntax

'Declaration
Public Function ContainerFromIndex ( _
    index As Integer _
) As DependencyObject
public DependencyObject ContainerFromIndex(
    int index
)

Parameters

  • index
    Type: System.Int32
    The index of the item to retrieve.

Return Value

Type: System.Windows.DependencyObject
The container for the item at the specified index within the item collection, if the item has a container; otherwise, nulla null reference (Nothing in Visual Basic).

Remarks

If there is no item at the specified index or the item has no container, the ContainerFromIndex method returns nulla null reference (Nothing in Visual Basic).

Examples

The following example shows how to retrieve an ItemContainerGenerator for a TreeView object and use the ContainerFromIndex method.

Run this sample

Public Sub New()
    InitializeComponent()
    Dim myItems As String() = New String() {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
    myTreeView.DataContext = myItems
End Sub
Shared count As Integer = 1
Private Sub Button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim item As TreeViewItem = DirectCast(myTreeView.ItemContainerGenerator.ContainerFromIndex(3), TreeViewItem)
    item.IsExpanded = True
    If count < 5 Then
        item.Items.Add("Child " & count.ToString())
        count += 1
    End If
End Sub
public MainPage()
{
    InitializeComponent();
    string[] myItems = new string[]{"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"};
    myTreeView.DataContext = myItems;
}
static int count = 1;
private void Button_Click(object sender, RoutedEventArgs e)
{
    TreeViewItem item = (TreeViewItem)myTreeView.ItemContainerGenerator.ContainerFromIndex(3);
    item.IsExpanded = true;
    if (count < 5)
    {
        item.Items.Add("Child " + count.ToString());
        count++;
    }
}
<StackPanel x:Name="LayoutRoot" Background="White">
    <sdk:TreeView x:Name="myTreeView" Width="200" ItemsSource="{Binding}" Margin="5"/>
    <Button Content="Add Child to Item 4" Width="150" Click="Button_Click"/>
</StackPanel>

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.