다음을 통해 공유


방법: 이름에 따라 요소 찾기

이 예제에서는 FindName 메서드를 사용하여 해당 Name 값으로 요소를 찾는 방법을 설명합니다.

예시

이 예제에서는 이름으로 특정 요소를 찾는 메서드를 단추의 이벤트 처리기로 작성합니다. stackPanel는 검색되는 루트 FrameworkElementName이며, 이후에 예제 메서드는 발견된 요소를 TextBlock으로 캐스팅하고 TextBlock 시각적 UI 중 하나를 변경하여 해당 요소를 시각적으로 표시합니다.

void Find(object sender, RoutedEventArgs e)
{
    object wantedNode = stackPanel.FindName("dog");
    if (wantedNode is TextBlock)
    {
        // Following executed if Text element was found.
        TextBlock wantedChild = wantedNode as TextBlock;
        wantedChild.Foreground = Brushes.Blue;
    }
}
Private Sub Find(ByVal sender As Object, ByVal e As RoutedEventArgs)
    Dim wantedNode As Object = stackPanel.FindName("dog")
    If TypeOf wantedNode Is TextBlock Then
        ' Following executed if Text element was found.
        Dim wantedChild As TextBlock = TryCast(wantedNode, TextBlock)
        wantedChild.Foreground = Brushes.Blue
    End If
End Sub