我有一个简单的TextBox,其样式为“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,为什么?
答案 0 :(得分:2)
通过“代码隐藏”,看起来你指的是窗口或视图的代码隐藏:包含文本框的东西。因此,Template
属性将引用此容器的模板,而不是文本框的模板。我会子类TextBox
并在其代码隐藏中公开这两个属性,或者指定您在所讨论的特定文本框的模板之后。即:
private Popup Popup
{
get { return TextBox.Template.FindName("PART_Popup", TextBox) as Popup; }
}
答案 1 :(得分:2)
在XAML中,您可以创建一个普通的TextBox并对其进行样式设置,在代码后面有this.Template
&amp; this
,这应该是怎么回事? this
实际上不是TextBox
。
答案 2 :(得分:0)
就我而言,这是一个奇怪的问题。代码适用于前两个按钮,但第三个按钮给我一个例外作为'演示者; object为null!
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";