Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Find the Index of an Element

This example shows how to find the index number of a newly added element by using the IndexOf method.

Example

The following example defines a host DockPanel element in Extensible Application Markup Language (XAML) and uses a Button to invoke the FindIndex custom method.

<DockPanel Name="ParentElement">

    <TextBlock DockPanel.Dock="Top" Name="TxtDisplay"></TextBlock>

    <Button DockPanel.Dock="Top" Click="FindIndex">What is the Index Number
        of the Element Just Added?</Button>
    <DockPanel Name="MainDisplayPanel">
        <TextBlock DockPanel.Dock="Top">Text 1</TextBlock>
        <TextBlock DockPanel.Dock="Top">Text 2</TextBlock>
    </DockPanel>
</DockPanel>

The related events are handled by using code behind. The index position of the element is reported back as a text string.

private int c_counter = 0;
void FindIndex(object sender, RoutedEventArgs e)
{
    c_counter+=1;
    // Create a new Text element.
    TextBlock newText = new TextBlock();
    // Add this element to the UIElementCollection of the DockPanel element.
    MainDisplayPanel.Children.Add(newText);
    // Add a text node under the Text element. This text is displayed. 
    newText.Text = "New element #" + c_counter;
    DockPanel.SetDock(newText,Dock.Top);
    // Display the Index number of the new element.    
    TxtDisplay.Text = "The Index of the new element is " +  MainDisplayPanel.Children.IndexOf(newText);
}

See Also

Community Additions

ADD
Show:
© 2015 Microsoft