Condividi tramite


Procedura: trovare l'indice di un elemento

Aggiornamento: novembre 2007

In questo esempio viene illustrato come trovare il numero di indice di un elemento appena aggiunto utilizzando il metodo IndexOf.

Esempio

Nell'esempio seguente viene definito un elemento DockPanel host in Extensible Application Markup Language (XAML) e viene utilizzato un oggetto Button per richiamare il metodo personalizzato FindIndex.

<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>

Gli eventi correlati vengono gestiti tramite code-behind. La posizione dell'elemento nell'indice viene indicata sotto forma di stringa di testo.

   Dim c_counter as Integer = 0
    Private Sub FindIndex(ByVal sender As Object, ByVal args As RoutedEventArgs)
        Try
            Dim newText As TextBlock = New TextBlock()
            c_counter = c_counter + 1
            ' 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 #" & CStr(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)
        Catch ex As System.Exception
            System.Windows.MessageBox.Show(ex.Message)
        End Try
    End Sub
     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);
        }

Vedere anche

Concetti

Cenni preliminari sugli elementi Panel

Riferimenti

UIElementCollection

UIElement

DockPanel