0

我有一个样式为“AutoCompleteTextBox”的简单文本框:

<TextBox Name="TextBox" Style="{StaticResource AutoCompleteTextBox}" />

样式位于我的资源字典中:

<Style x:Key="AutoCompleteTextBox" TargetType="{x:Type TextBox}">
    <Setter Property="KeyboardNavigation.TabNavigation" Value="None" />
    <Setter Property="FocusVisualStyle" Value="{x:Null}" />
    <Setter Property="AllowDrop" Value="true" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBox}">
                <Grid>
                    <Border x:Name="Bd" SnapsToDevicePixels="true">
                        <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </Border>
                    <Popup x:Name="PART_Popup" StaysOpen="False" Placement="Bottom" IsOpen="False">
                        <ListBox x:Name="PART_ListBox" HorizontalContentAlignment="Stretch"/>
                    </Popup>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

在我的代码隐藏文件中,我有两个吸气剂:

private Popup Popup
{
    get { return Template.FindName("PART_Popup", this) as Popup; }
}
private ListBox ItemList
{
    get { return Template.FindName("PART_ListBox", this) as ListBox; }
}

和文本框加载事件:

void TextBox_Loaded(object sender, RoutedEventArgs e)
{
    var popup = Popup;

    var itemlist = ItemList;
}

现在我有一个问题,Popup并且ItemList总是返回 null,为什么?

4

3 回答 3

2

通过“代码隐藏”,您似乎指的是窗口或视图的代码隐藏:包含文本框的东西。因此,该Template属性将引用此容器的模板,而不是文本框的模板。我将子类化TextBox并在其代码隐藏中公开这两个属性,或者指定您在相关特定文本框的模板之后。IE:

private Popup Popup
{
    get { return TextBox.Template.FindName("PART_Popup", TextBox) as Popup; }
}
于 2012-09-24T09:16:29.763 回答
2

在 XAML 中,您创建一个普通的 TextBox 并为其设置样式,在您后面的代码中有this.Template& this,这应该如何工作?没有办法,this实际上是TextBox.

于 2012-09-24T09:17:18.820 回答
0

就我而言,这是一个奇怪的问题。前两个按钮的代码工作正常,但第三个按钮给了我一个例外作为“演示者”;对象为空!

ContentPresenter presenter = new ContentPresenter();
        presenter = buttonUsersSave.Template.FindName("Presenter", buttonUsersSave) as ContentPresenter;
        presenter.Content = "Save";
        presenter = buttonUsersUpdate.Template.FindName("Presenter", buttonUsersUpdate) as ContentPresenter ;
        presenter.Content = "Update";
        presenter = buttonUserAuthSave.Template.FindName("Presenter", buttonUserAuthSave) as ContentPresenter;
        presenter.Content = "Save";
于 2016-06-02T20:53:07.017 回答