locked
how to use FrameworkElement.FindName RRS feed

  • Question

  • According to MSDN FrameworkElement.FindName searches recursively till it finds a element by the given name.

    "If this element has child elements, these child elements are all searched recursively for the requested named element."

    I believe I should be able to use this to get the textbox part of a combobox, example:

    TextBox tt = combo.FindName("PART_EditableTextBox") as TextBox;

    But it doesn't work. I tested a bit more and turns out FindName doesn't have the recursive behavior the docs says. This code works:

    FrameworkElement grid = VisualTreeHelper.GetChild(combo, 0) as FrameworkElement;
    Border bd = grid.FindName("Bd") as Border;
    grid =
    VisualTreeHelper.GetChild(bd, 0) as FrameworkElement;
    TextBox text = grid.FindName("PART_EditableTextBox") as TextBox;

    Is that a known bug ? (in the doc or implemention)
    Is there a easy way to get the textbox part of the combobox ?

    Thanks
    Felipe

    Wednesday, October 25, 2006 10:20 PM

Answers

  • To get the reference to the elements within a template, you can call Control.Template.FindName() method.

    Sheva
    Thursday, October 26, 2006 11:33 AM

All replies

  • I believe the problem is that names within a Template are scoped only to the Template and are not visible to the logical tree under which the Template resides.  Thus, your query for "PART_EditableTextBox" isn't found because the combo's logical children do not include its Template where the text box is defined.  In your second piece of code you're walking the Visual tree - a lower level construct than the logical tree - to bridge the two worlds (from the logical tree into the Template), and thus a query from within the Template works as you'd like. 

    This is actually an intentional design decision - ControlTemplates are designed to be treated as parametized black boxes.  There are a number of top level properties will which affect the appearance of a template (IsEnabled, etc, etc), but it generally not a great idea to "crack open" a Template.

    If you can describe what you're trying to accomplish by retrieving the TextBox, we may be able to help you in other ways, and/or create a feature request to enable your scenario.

    -Adam Smith [MS]

    Wednesday, October 25, 2006 10:55 PM
  • To get the reference to the elements within a template, you can call Control.Template.FindName() method.

    Sheva
    Thursday, October 26, 2006 11:33 AM