What you're asking for is to be able to use content in the two different ways it is commonly used, but at the same time with one control. You can do this, but just need 2 different content properties. You could define your own secondary content property set but it's much easier to just derive from HeaderContentControl
, which already does exactly that for you with its Header
properties.
To allow users of the control to treat it like a normal ContentControl
and just enclose content in the tags you can use the Header
content as the part that you define UserControl
style and can access from code-behind. Inside that content you can just put a ContentPresenter
wherever you want to receive the external Content
. You then also need to adjust the ControlTemplate
to only show the Header
content (Content
will be inside the Header
part remember).
<HeaderedContentControl x:Class="WpfApp.MyRulerControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp">
<HeaderedContentControl.Template>
<ControlTemplate TargetType="{x:Type local:MyRulerControl}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter ContentSource="Header"/>
</Border>
</ControlTemplate>
</HeaderedContentControl.Template>
<HeaderedContentControl.Header>
<StackPanel>
<Border x:Name="Ruler1" Height="20"/>
<ContentPresenter
Content="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyRulerControl}}, Path=Content}"
ContentTemplate="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MyRulerControl}}, Path=ContentTemplate}"/>
<Border x:Name="Ruler2" Height="20"/>
</StackPanel>
</HeaderedContentControl.Header>
</HeaderedContentControl>
Now you can use the control like normal:
<local:MyRulerControl>
<TextBlock Text="External content here"/>
</local:MyRulerControl>
You can also get to anything inside that Header
section from code-behind:
public MyRulerControl()
{
InitializeComponent();
Ruler1.Background = Brushes.Red;
Ruler2.Background = Brushes.Blue;
}