如何:按名称查找元素

此示例介绍如何如何使用 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