Does anyone have a simple example of a UserControl with a single ContentPresenter?

devuxer picture devuxer · Oct 19, 2009 · Viewed 7.1k times · Source

So far, I have this:

<UserControl
    x:Class="MyConcept.ExpanderPanel"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Border
            Style="{StaticResource Border_PanelStyle}"
            CornerRadius="3" />
        <ContentPresenter />
    </Grid>
</UserControl>

Sample usage of this UserControl:

<nc:ExpanderPanel
    Grid.Row="0">
    <Expander
        IsExpanded="True"
        Header="NMT Users">
        <StackPanel>
            ...
        </StackPanel>
    </Expander>
</nc:ExpanderPanel>

Discussion

If I run this, I see nothing. No content is presented, not even the border that is built into the UserControl.

I thought maybe I needed to make the ContentPresenter a dependency property, but I couldn't figure out how I would link the property to the ContentPresenter in the UserControl's XAML.

Can someone provide a simple example that shows how to build a UserControl (or some kind of custom control) with a single ContentPresenter?

Answer

Muad&#39;Dib picture Muad'Dib · Oct 19, 2009

ContentPresenters are main used in ControlTemplates and bound with a TemplateBinding to the ContentControl.Content. from this site... a control template for a button that uses a ContentPresenter

<Style TargetType="{x:Type Button}">
  <Setter Property="Background" Value="White" />
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate>
        <Grid>
          <Rectangle Fill="{TemplateBinding Property=Background}" />
            <ContentPresenter
              Content="{TemplateBinding Property=ContentControl.Content}" />
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>