Michael Rosefield
Michael Rosefield

Reputation: 471

WPF: cannot access ComboBox's TextBox with FindName

I saw that I can access the templated parts of a ComboBox (the TextBox, PopUp and Button) via the FindName method.

The TextBox should be accessible by using cb.FindName("PART_EditableTextBox"), however, this always returns null for me.

As per melya's suggestion, I have tried using cb.Template.FindName("PART_EditableTextBox", cb); instead -- this works on a simple test app, but not my own.

The difference, perhaps, is that I'm trying to do this before the ComboBox is loaded or initialised (I'm developing an Attached Property that adds functionality to TextBoxes/ComboBoxes).

cb.ItemTemplate shows as null.

Unfortunately, the obvious solution of trying cb.ApplyTemplate() returns false and doesn't do anything.

Is there anything I can do?

Upvotes: 4

Views: 1334

Answers (2)

Eric L
Eric L

Reputation: 21

I know I'm late to the party here, but thought I'd answer in case anyone else ends up here, like I did.

In my case, I was working on a custom ComboBox control. I followed other suggestions to handle this in the Loaded event, but (like the OP), kept getting a null return. Eventually, I figured out that Loaded was too early. My control was displayed on a tab, which was not initially visible.

Instead, overriding OnApplyTemplate was a better fit for me, since this comes after the Loaded event (when the template becomes available). The code I used was as follows:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    var textBox = Template.FindName("PART_EditableTextBox", this) as TextBox;
}

Upvotes: 2

iceberg
iceberg

Reputation: 596

Try this way

cb.Template.FindName("PART_EditableTextBox", cb);

Upvotes: 1

Related Questions