Search for an element by using Panel.FindName()
<StackPanel Name="root"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.FEFindName">
<StackPanel.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Height" Value="20"/>
<Setter Property="Width" Value="250"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="FontSize" Value="20"/>
</Style>
</StackPanel.Resources>
<Button Click="Find">Find element with the ID "dog" and change color</Button>
<StackPanel Name="stackPanel">
<TextBlock Name="cat">Cat</TextBlock>
<TextBlock Name="dog">Dog</TextBlock>
<TextBlock Name="fish">Fish</TextBlock>
</StackPanel>
</StackPanel>
//File:Window.xaml.vb
Imports System
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media
Namespace WpfApplication1
Public Partial Class FEFindName
Private Sub Find(sender As Object, e As RoutedEventArgs)
Dim wantedNode As Object = stackPanel.FindName("dog")
If TypeOf wantedNode Is TextBlock Then
Dim wantedChild As TextBlock = TryCast(wantedNode, TextBlock)
wantedChild.Foreground = Brushes.Blue
End If
End Sub
End Class
End Namespace
Related examples in the same category