WPF: cannot access ComboBox's TextBox with FindName

做~自己de王妃 提交于 2019-12-23 19:14:54

问题


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?


回答1:


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;
}



回答2:


Try this way

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


来源:https://stackoverflow.com/questions/34266689/wpf-cannot-access-comboboxs-textbox-with-findname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!