Search code examples
wpfxamluser-controlscontentpresenter

Include a UserControl with Content


I've created a UserControl. I would like to include it with this code:

<UserControl1 Header="Heading">
    <TextBlock Text="My Content" />
</UserControl1>

That's the UserControl:

<UserControl x:Class="WpfApplication1.UserControl1"
             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" MinHeight="200"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <Style TargetType="ToggleButton">
            <!-- ... -->
        </Style>        
    </UserControl.Resources>
    <StackPanel>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Path=Header}" Grid.Column="0" />
            <ToggleButton Name="ToggleButton" IsChecked="True" Grid.Column="2" />
        </Grid>
        <Rectangle Stroke="#c3c3c3" StrokeThickness="1" Height="1" StrokeDashArray="4 4" SnapsToDevicePixels="True" Focusable="False" />
        <!-- Content -->
        <ContentControl>
            <ContentPresenter/>
        </ContentControl>
    </StackPanel>
</UserControl>

Now to my problem:

If I integrate it with the following code,

<UserControl1 Header="Heading">
    <TextBlock Text="My Content" />
</UserControl1>

I receive that as result:

enter image description here

That's not what I want.

But when i integrate it with this code, I've got the desired result.

<UserControls:UserControl1 Header="Heading" />

enter image description here

What's wrong at my first way?


Solution

  • There is nothing wrong with the first way. It simply creates a UserControl1 and sets the content to a TextBlock, hereby overriding the content you set in the definition. The second way creates a UserControl1 and leaves the content as is.