无法获取从 ComboBox 继承的自定义控件中的文本框的引用?



这是我尝试使用 Template.FindName 获取TextBox的代码示例,但结果我得到了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>

我发现了一个具有类似null值问题的问题。但正如你从我的代码中看到的那样,这些答案对我不起作用。

如何获取文本框控件的引用?为什么它不起作用?

最初,

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

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

最新更新