如何:按名称查找元素

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

示例

在本示例中,按名称查找特定元素的方法编写为按钮的事件处理程序。 stackPanel 是所搜索的根 FrameworkElementName,之后示例方法通过将找到的元素强制转换为 TextBlock 并更改 TextBlock 的某个可见 UI 属性,以可视方式指示找到的元素。

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