Style DataGridColumnHeader with Styles in WPF
Hi i am trying to implement a way to filter my records in a DataGrid. My idea is to put TextBoxes in the Header of each Column.
I am doing this depending if a ToggleButton is pressed or not, but i am having a problem in the way that i am applying the style in the Header.
If i apply the style inside the DataGridColumn like this:
<DataGridTextColumn>
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
(...)
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
It will work perfectly!
But if try to put this in a Style i am doing it like this:
<Style TargetType="{x:Type DataGridTextColumn}">
<Setter Property="Template">
<Cont开发者_StackOverflow中文版rolTemplate>
(...)
</ControlTemplate>
</Setter>
</Style>
By using the ControlTemplate we will override the background and all the Default layout of DataGridColumnHeader and i don't want that. How i can i do this?
I am really tring to do this to avoid repeat code in XAML.
Thanks in advance!
If the only reason you are not using the DataTemplate approach is because you want to define it once (at some central location) and then use it at multiple places (e.g. multiple columns), you can move that DataTemplate to the resources section, assign it a resource key and use it whereever you want.
Here's how:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate x:Key="MySpecialHeaderTemplate">
<TextBox Text="Search..." />
</DataTemplate>
</Window.Resources>
<Grid>
<DataGrid>
<DataGrid.Columns>
<DataGridTextColumn
Binding="{Binding Id}" />
<DataGridTextColumn HeaderTemplate="{StaticResource MySpecialHeaderTemplate}"
Binding="{Binding Name}" />
<DataGridTextColumn HeaderTemplate="{StaticResource MySpecialHeaderTemplate}"
Binding="{Binding Age}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
精彩评论