WPF:无法使用FindName访问ComboBox的TextBox [英] WPF: cannot access ComboBox's TextBox with FindName

查看:299
本文介绍了WPF:无法使用FindName访问ComboBox的TextBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到我可以访问 ComboBox TextBox PopUp Button )通过 FindName 方法。

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

应该使用 cb.FindName( PART_EditableTextBox) TextBox 进行访问/ code>,但是这总是为我返回 null

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

根据melya的建议,我尝试使用 cb.Template.FindName( PART_EditableTextBox,cb); 代替-可以在简单的测试应用程序上使用,但不适用于我自己的应用程序。

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.

也许不同之处在于,我正在尝试加载或初始化 ComboBox 之前执行此操作(我正在开发附加属性,可为 TextBoxes / ComboBoxes 添加功能。

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 显示为 null

不幸的是,尝试 cb.ApplyTemplate()的明显解决方案返回 false 却什么也没做。

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

我能做些什么吗?

推荐答案

我知道我在这里参加聚会迟到了,但是我想我会回答的话,以防其他人像我一样呆在这里。

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

就我而言,我正在研究自定义ComboBox控件。我遵循了其他建议来在Loaded事件中处理此问题,但是(如OP)始终保持null返回。最终,我发现Loaded还为时过早。我的控件显示在最初不可见的选项卡上。

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.

相反,重写OnApplyTemplate更适合我,因为这是在Loaded事件之后(当模板可用)。我使用的代码如下:

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

这篇关于WPF:无法使用FindName访问ComboBox的TextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆