Search code examples
c#wpfxamlbindingcontentcontrol

ContentControl not showing Content


I have a custom ContentControl which has a fixed XAML layout like a UserControl (Rather than the usual applied generic template).

Previously this layout had no extra markup, so it was literally:

<ContentControl x:Class="MyControls.CustomViewControl"
             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="300" d:DesignWidth="300">
</ContentControl>

This worked fine.

I now want to put a border around the content, so I have changed the XAML to:

<ContentControl x:Class="MyControls.CustomViewControl"
             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="300" d:DesignWidth="300">
    <ContentControl.Template>
        <ControlTemplate>
            <Border BorderThickness="5" BorderBrush="LightGreen">
                <ContentPresenter />
            </Border>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

This shows the border, but no content.

I tried supplying an explicit binding for ContentPresenter:

<ContentPresenter Content="{Binding Path=Content, RelativeSource={RelativeSource Self}}"/>

But this made no difference.

Setting an explicit Content does work:

<ContentPresenter Content="TEST" />

Anyone know why the Content binding doesn't work? I guess I could fall back to the usual generic template but it would be easier if I could just do it directly like a UserControl.


Solution

  • Add TargetType for Control Template

    <ContentControl.Template>
        <ControlTemplate  TargetType="Button">
            <Border BorderThickness="5" BorderBrush="LightGreen">
                <ContentPresenter />
            </Border>
        </ControlTemplate>
    </ContentControl.Template>