无法引用从ComboBox继承的CustomControl中的TextBox?

时间:2018-01-10 13:02:07

标签: c# wpf combobox

以下是我尝试使用TextBox获取Template.FindName的代码示例,但结果我得到null

public class MeasureComboBox : ComboBox
{
    #region FIELDS
    /// <summary>
    /// TextBox that bilongs to ComboBox control. 
    /// </summary>
    private TextBox TextBox;
    #endregion

    static MeasureComboBox()
    {
    }

    public MeasureComboBox()
    {

    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        // Why this.TextBox is equal to null here?
        this.TextBox = this.Template.FindName("PART_EditableTextBox", this) as TextBox;
    }
}

XAML:

<UserControl x:Class="Parser.Controls.OlxUrlCarMaxPriceParameters"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Parser.Controls"
             xmlns:w="clr-namespace:Parser.CustomControls"
             mc:Ignorable="d" 
             d:DesignWidth="300">
    <StackPanel>
        <w:MeasureComboBox/> // Here is my custom control
    </StackPanel>
</UserControl>

我发现question有类似null值的问题。但正如您从我的代码中可以看到的那样,这些答案对我来说并不起作用。

如何获取参考TextBox控件?为什么它不起作用?

1 个答案:

答案 0 :(得分:2)

最初我认为您的组合框是使用自定义模板自定义的;如果要获取作为默认组合框模板的一部分提供的文本框,则必须确保将IsEditable属性设置为true,否则不会创建文本框。所以:

<StackPanel>
    <w:MeasureComboBox IsEditable="True" /> // Here is my custom control
</StackPanel>