Edit

Share via


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.

Example

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

Note

The FindName method only finds elements that are part of the XAML namescope. If you add an element to the object tree programmatically after XAML is loaded, the element's Name or x:Name value doesn't automatically register in the XAML namescope. To make a dynamically added element findable by name, call RegisterName on the XAML namescope (typically the page or window root) before adding the element to the parent container. For more information, see XAML Namescopes.