CustomUserControl.xaml.cs
public partial class CustomUserControl : UserControl
{
public CustomUserControl ()
{
InitializeComponent();
var style = (Style)FindResource("Styling");
Style = style;
}
public static readonly DependencyProperty ItemHeaderTemplateProperty = DependencyProperty.Register(nameof(ItemHeaderTemplate), typeof(DataTemplate), typeof(CustomUserControl), new PropertyMetadata(default(DataTemplate)));
public DataTemplate ItemHeaderTemplate
{
get => (DataTemplate)GetValue(ItemHeaderTemplateProperty);
set => SetValue(ItemHeaderTemplateProperty, value);
}
}
CustomUserControl.xaml
<Style x:Key="Styling" TargetType="{x:Type local:CustomUserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomUserControl}">
<!-- This works -->
<ContentControl ContentTemplate="{TemplateBinding ItemHeaderTemplate}"/>
<TabControl Name="TestName" ItemsSource="{Binding Items}">
<TabControl.ContentTemplate>
<DataTemplate>
<DockPanel>
<!-- These don't work -->
<ContentControl ContentTemplate="{TemplateBinding ItemHeaderTemplate}"/>
<ContentControl ContentTemplate="{Binding ElementName=TestName, Path=DataContext.ItemHeaderTemplate}"/>
<ContentControl ContentTemplate="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ItemHeaderTemplate}"/>
</DockPanel>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The reference to ItemHeaderTemplate outside the TabControl works properly, but none of the references to ItemHeaderTemplate inside the TabControl work.
What is the proper way to access a parent control's property from within a child control in a ControlTemplate?
CodePudding user response:
I realized the answer to my own question was pretty simple.
I just needed to directly set the ContentTemplate.
<Style x:Key="Styling" TargetType="{x:Type local:CustomUserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomUserControl}">
<!-- This works -->
<ContentControl ContentTemplate="{TemplateBinding ItemHeaderTemplate}"/>
<!-- This now works too -->
<TabControl ItemsSource="{Binding Items}"
ContentTemplate="{TemplateBinding ItemHeaderTemplate}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>