How can I find WPF controls by name or type?

You can also find an element by name using FrameworkElement.FindName(string).


<UserControl ...>
    <TextBlock x:Name="myTextBlock" />

In the code-behind file, you could write:

var myTextBlock = (TextBlock)this.FindName("myTextBlock");

Of course, because it’s defined using x:Name, you could just reference the generated field, but perhaps you want to look it up dynamically rather than statically.

This approach is also available for templates, in which the named item appears multiple times (once per usage of the template).

Leave a Comment