ContentPresenter Is Not Set When Using a ControlTemplate for a ContentControl

I encountered a problem today, the solution to which some of you may find worth keeping note of.

One of the user controls in my Window had to sit inside a fancy container. Obviously, I didn’t want to mix plainly visual elements with my logical ones (and also allow the graphic designers to work in peace), so instead I wrapped my element with a ContentControl and gave it a style:

<ContentControl Style="{StaticResource userControlDecorationStyle}">
    <MyAwesomeUserControl />
</ContentControl>

I then went to my ResourceDictionary and gave the style a ControlTemplate which contained the fancy container and a ContentPresenter where my user control was meant to be:

<Style x:Key="userControlDecorationStyle" TargetType="ContentControl">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <FluffyBunniesBorder ...>
                    <ContentPresenter />
                </FluffyBunniesBorder>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Running it didn’t produce the result I wanted – the visual tree showed the ContentPresenter as a leaf in the tree, instead of replacing it with my user control.

After a bit of work, I found the solution to this. All I had to do was to let the ControlTemplate know it’s being used on a ContentControl:

<!-- ... -->
<Setter.Value>
    <ControlTemplate TargetType="ContentControl">
        <FluffyBunniesBorder ...>
            <!-- ... -->

And presto, my user control appears.

Advertisements

2 thoughts on “ContentPresenter Is Not Set When Using a ControlTemplate for a ContentControl

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s