我想在每个列的标题中创建一个带gridview
的自定义header and filter
。我在WPF中成功创建了一个GridViewColumnHeader模板,如下所示:
<Style TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Border BorderThickness="0,0,0,1" BorderBrush="Black" Background="Transparent">
<StackPanel Orientation="Vertical" Margin="1">
<TextBlock Padding="5,5,5,0" Text="{TemplateBinding Content}" Width="{TemplateBinding Width}" TextAlignment="Center" />
<TextBox x:Name="HeaderSearch" Padding="5,5,5,0" Width="{TemplateBinding Width}" TextAlignment="Center" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Foreground" Value="Black" />
</Style>
<ScrollViewer Grid.Column="1">
<ListView>
<ListView.View>
<GridView >
<GridViewColumn Header="Code" Width="100"/>
<GridViewColumn Header="Name" Width="100"/>
<GridViewColumn Header="Description" Width="100"/>
</GridView>
</ListView.View>
</ListView>
</ScrollViewer>
如何在后面的代码中访问文本框?
提前致谢。
答案 0 :(得分:1)
添加GotFocus
或Loaded
事件处理程序
<TextBox x:Name="HeaderSearch" Padding="5,5,5,0"
Width="{TemplateBinding Width}" TextAlignment="Center"
GotFocus="HeaderSearch_GotFocus" />
TextBox CodeHeaderSearch;
TextBox NameHeaderSearch;
private void HeaderSearch_GotFocus(object sender, RoutedEventArgs e)
{
TextBox t = sender as TextBox;
var header = GetGridViewColumnHeader(t);
if (header == "Code")
{
CodeHeaderSearch = sender as TextBox;
}
else if (header == "Name")
{
NameHeaderSearch = sender as TextBox;
}
// ....
}
private string GetGridViewColumnHeader(TextBox t)
{
var GridViewColumn = FindParent<GridViewColumnHeader>(t);
return GridViewColumn.Column.Header as string;
}
public static T FindParent<T>(DependencyObject child) where T : DependencyObject
{
//get parent item
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
return parent;
else
return FindParent<T>(parentObject);
}