#104 – Using FindName to Find Named Children of a Control

When you create a XAML file for WPF in the normal Visual Studio environment, any control for which you provide a Name property will automatically get a backing variable defined that will let you reference the instance of that control directly from your code-behind.

But there are times when you don’t already have a reference variable pointing to a particular control, but only to the root element that exists at the top of the XAML file.  Instead of trying to navigate all the way down from the root element to the child that you’re looking for, you can use the FindName method.

In the example below, our root element is a Window and we want to get a reference to a child Label control that exists as a descendent of the window instance.

 Label myLabel = (Label)this.FindName("label1");

We pass in the name of the control, which we set in the XAML with the Name property.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #104 – Using FindName to Find Named Children of a Control

  1. Basarat Ali says:

    For your readers that might not know. It comes in handy when you load a xaml file from your code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: