.NET Framework Class Library
FrameworkTemplate..::.FindName Method

Finds the element associated with the specified name defined within this template.

Namespace:  System.Windows
Assembly:  PresentationFramework (in PresentationFramework.dll)
Syntax

Visual Basic (Declaration)
Public Function FindName ( _
    name As String, _
    templatedParent As FrameworkElement _
) As Object
Visual Basic (Usage)
Dim instance As FrameworkTemplate
Dim name As String
Dim templatedParent As FrameworkElement
Dim returnValue As Object

returnValue = instance.FindName(name, _
    templatedParent)
C#
public Object FindName(
    string name,
    FrameworkElement templatedParent
)
Visual C++
public:
Object^ FindName(
    String^ name, 
    FrameworkElement^ templatedParent
)
JScript
public function FindName(
    name : String, 
    templatedParent : FrameworkElement
) : Object
XAML
You cannot use methods in XAML.

Parameters

name
Type: System..::.String
The string name.
templatedParent
Type: System.Windows..::.FrameworkElement
The context of the FrameworkElement where this template is applied.

Return Value

Type: System..::.Object
The element associated with the specified name.
Remarks

For more information, see "Namescopes in Styles and Templates" in WPF XAML Namescopes.

Examples

This example shows how to find elements that are generated by a DataTemplate.

In this example, there is a ListBox that is bound to some XML data:

XAML
<ListBox Name="myListBox" ItemTemplate="{StaticResource myDataTemplate}"
         IsSynchronizedWithCurrentItem="True">
  <ListBox.ItemsSource>
    <Binding Source="{StaticResource InventoryData}" XPath="Books/Book"/>
  </ListBox.ItemsSource>
</ListBox>

The ListBox uses the following DataTemplate:

XAML
<DataTemplate x:Key="myDataTemplate">
  <TextBlock Name="textBlock" FontSize="14" Foreground="Blue">
    <TextBlock.Text>
      <Binding XPath="Title"/>
    </TextBlock.Text>
  </TextBlock>
</DataTemplate>

If you want to retrieve the TextBlock element generated by the DataTemplate of a certain ListBoxItem, you need to get the ListBoxItem, find the ContentPresenter within that ListBoxItem, and then call FindName on the DataTemplate that is set on that ContentPresenter. The following example shows how to perform those steps. For demonstration purposes, this example creates a message box that shows the text content of the DataTemplate-generated text block.

C#
// Getting the currently selected ListBoxItem
// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
ListBoxItem myListBoxItem =
    (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));

// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", myContentPresenter);

// Do something to the DataTemplate-generated TextBlock
MessageBox.Show("The text of the TextBlock of the selected list item: "
    + myTextBlock.Text);

The following is the implementation of FindVisualChild, which uses the VisualTreeHelper methods:

C#
private childItem FindVisualChild<childItem>(DependencyObject obj)
    where childItem : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(obj, i);
        if (child != null && child is childItem)
            return (childItem)child;
        else
        {
            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
                return childOfChild;
        }
    }
    return null;
}

For the complete sample, see Finding Template-Generated Elements Sample.

More Code

How to: Find ControlTemplate-Generated Elements This example shows how to find elements that are generated by a ControlTemplate.
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0
See Also

Reference

Tags :


Community Content

Ken Smith
This is astonishingly complicated.
I'm constantly astonished how difficult WPF/XAML makes it to do very simple things. I've got a ListBoxItem, and I want to find the name of a control within that item. This is a very common scenario, and I expected to be able to do that with one line of code: something like this:

TextBlock myTextBlock = myListBoxItem.FindName("myTextBlock");

Instead, according to the example above, it takes 14+ lines of code to do what you should be able to do in one. And the content of those 14 lines of code would be completely undiscoverable to anyone who didn't have an extremely good understanding of how WPF works under the hood.

If this was an isolated example, it would be one thing: but in the last month of learning WPF (I'm admittedly still a newbie), I've come across dozens of similar examples, of things that should be simple to do, but which are made very difficult either by the structure of XAML, or by the immaturity of the framework (despite the three years that MS has had to fix it). Extrapolate this across even a fairly simple application, and you've got all the makings of a horrific maintenance nightmare, not to mention untold hours of troubleshooting and research. In all the code reviews at Microsoft, did nobody stop and ask, "Does anybody else think this is too complicated?"

WPF and XAML, despite all the hooplah and hype, still seem to be a long way from prime time, in my book. And I'm not yet seeing a ton of evidence that VS2010/.NET4.0 is going to fix this.

Page view tracker