Find Controls by Name in WPF


FindName method of FrameworkElement class is used to find elements or controls by their Name properties. The FrameworkElement class is mother of all controls in WPF.

Here is a Window with a Button, a TextBox, and a ListBox control.

<Window x:Class="FindControlByNameSample.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Window1" Height="305" Width="508">

    <Grid Name="LayoutRoot">

        <Button Content="Find By Name" Height="35" HorizontalAlignment="Left" Margin="18,23,0,0"

                Name="FindNameButton" VerticalAlignment="Top" Width="144" Click="FindNameButton_Click" />

        <TextBox Height="39" HorizontalAlignment="Left" Margin="202,21,0,0" Name="TextBox1"

                 VerticalAlignment="Top" Width="184" />

        <ListBox Height="146" HorizontalAlignment="Left" Margin="18,98,0,0" Name="listBox1"

                 VerticalAlignment="Top" Width="179" />

    </Grid>

</Window>

 

The following code snippet is a button click event handler and calls FindName method of Grid to find the control by its name. The code takes control name from the TextBox and checks of the found control is a TextBox, ListBox, or Button and based on its type, code sets its properties.

private void FindNameButton_Click(object sender, RoutedEventArgs e)

{

    object item = LayoutRoot.FindName(TextBox1.Text);

    if (item is TextBox)

    {

        TextBox txt = (TextBox)item;

        txt.Text = "Aha! you found me!";

        txt.Background = new SolidColorBrush(Colors.LightYellow);

    }

    else if (item is ListBox)

    {

        ListBox lst = (ListBox)item;

        lst.Items.Add("Aha! you found me!");

    }

    else if (item is Button)

    {

        Button btn = (Button)item;

        btn.Content = "Aha! you found me!";

        btn.Background = new SolidColorBrush(Colors.LightSeaGreen);

    }

}

If you enter "TextBox1" in the TextBox and click Find By Name button, you will see output like Figure 1.

FindNameImg1.gif

Figure 1

Up Next
    Ebook Download
    View all
    Learn
    View all