다음을 통해 공유


방법: 요소의 인덱스 찾기

업데이트: 2007년 11월

이 예제에서는 IndexOf 메서드를 사용하여 새로 추가된 요소의 인덱스 번호를 찾는 방법을 보여 줍니다.

예제

다음 예제에서는 호스트 DockPanel 요소를 XAML(Extensible Application Markup Language)에 정의하고 Button을 사용하여 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>

연결된 이벤트는 코드 숨김을 사용하여 처리되며 요소의 인덱스 위치는 텍스트 문자열로 보고됩니다.

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

참고 항목

개념

Panel 개요

참조

UIElementCollection

UIElement

DockPanel