TecMan TecMan - 1 year ago 94
C# Question

ContentControl does not show content in ControlTemplate

I need to create a custom control similar to WPF GroupBox. I started from the standard WPF Custom Control Library template in VS 2015 and defined my CustomGroupBox control like this:

public class CustomGroupBox : ContentControl
static CustomGroupBox()
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomGroupBox), new FrameworkPropertyMetadata(typeof(CustomGroupBox)));

Then added the following minimal set of lines to develop my custom GroupBox according to the specification:

<Style TargetType="{x:Type local:CustomGroupBox}">
<Setter Property="Template">
<ControlTemplate TargetType="{x:Type local:CustomGroupBox}">
<Border Background="{TemplateBinding Background}"
BorderBrush="Gray" BorderThickness="3" CornerRadius="3">
<ContentControl />

To debug and develop, I created a test form for my custom control:

<Window x:Class="CustomGroupBoxClient.MainWindow"
Title="MainWindow" Height="350" Width="525">
<ctrl:CustomGroupBox Margin="5">
<StackPanel Orientation="Vertical">
<TextBlock>Text Block #1</TextBlock>
<TextBlock>Text Block #2</TextBlock>

However, when I launch this form, I see the border of my custom control but not the content (2 TextBlock's):

enter image description here

I've re-read many manuals and articles related to this topic, but still can't figure out why ContentControl in my ControlTemplate does not display the specified content. How to solve my problem?

Answer Source

Try using ContentPresenter instead of ContentControl in your template:

<ContentPresenter />

By default, ContentPresenter finds the Content property of its templated parent and displays whatever it finds there. You could change the name of the property it looks for by changing its ContentSource value...

<ContentPresenter ContentSource="FooBar" />

...but since you're inheriting from ContentControl, the default is probably what you want.