[英]WPF - Binding custom DataGridTextColumn template's Content property to parent's property
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. 首先,在离开WPF几年之后,我将重返WPF,我之前对WPF有所了解,并开发了一些窗口,但现在我已经生锈了。 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. 我正在尝试用过滤器标题构建一个DataGrid,现在我知道没有为此准备好的控件,需要创建它,而我已经开始使用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. 我的模板由左侧的Label控件(包含标题的标题)和右侧的DatePick控件组成,我将在过滤过程中使用该控件。 I am trying to get Label.Content property inside my template to pick the DataGridTextColumn.Header property value of template parent. 我试图在模板中获取Label.Content属性,以选择模板父级的DataGridTextColumn.Header属性值。
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. 我已经尝试了RelativeSource,TemplatedParent以及其他所有功能,但我在这里也找不到任何描述与我类似的问题或解决方案的帖子。 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: 绑定到DataContext
本身:
<Label ... Content="{Binding}" />
The DataContext
of a DataGridColumnHeader
is the Header
object itself, ie the string
in your case. DataGridColumnHeader
的DataContext
是Header
对象本身,即您所用的string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.