First of, I am coming back to WPF after several years of leaving it behind, I knew a little of it before and develop a few windows but now I am beyond rusty. I am trying to build a DataGrid with filter headers, now I understand that there isn't a ready made control for that and needs to be created, which I have started using a Template.
My template consists of a Label control to the left which contains the title of the header, and a DatePick control to the right which I will use as part of my filtering process. I am trying to get Label.Content property inside my template to pick the DataGridTextColumn.Header property value of template parent.
I have tried RelativeSource, TemplatedParent and everything else there is, I also couldn't find any post on here that described a similar issue to mine nor a solution. Any help would be greatly appreciated. Thanks.
My code
<UserControl x:Class="CustomControls.ReportsListingControl"
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"
mc:Ignorable="d"
d:DesignHeight="100" d:DesignWidth="600">
<UserControl.Resources>
<Style x:Key="ColumnHeaderStyle1" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DataGridColumnHeader">
<Grid Width="200" Height="35">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Column="0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="50"
Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridTextColumn}}, Path=Header}" />
<DatePicker Grid.Column="1"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Width="30"
BorderThickness="0" Text="" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid>
<DataGrid Name="DataGrid1" >
<DataGrid.Columns>
<DataGridTextColumn HeaderStyle="{StaticResource ColumnHeaderStyle1}" Header="The Text I want displayed in my template label" />
</DataGrid.Columns>
</DataGrid>
</Grid>
Bind to the DataContext
itself:
<Label ... Content="{Binding}" />
The DataContext
of a DataGridColumnHeader
is the Header
object itself, ie the string
in your case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.