如何:按元素名称查找元素

此示例介绍如何使用 FindName 该方法按其 Name 值查找元素。

示例:

在此示例中,按其名称查找特定元素的方法将编写为按钮的事件处理程序。 stackPanel 是正在搜索的根 FrameworkElementName,然后示例方法通过将该元素强制转换为 TextBlock,并更改其中一个 UI 可见属性,从而直观地指示出找到的 TextBlock 元素。

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