How to: Find an Element by Its Name

This example describes how to use the FindName method to find an element by its Name value.


In this example, the method to find a particular element by its name is written as the event handler of a button. stackPanel is the Name of the root FrameworkElement being searched, and the example method then visually indicates the found element by casting it as TextBlock and changing one of the TextBlock visible UI properties.

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