wpfcustom-controlscontentpresenter

WPF Custom Control can not take direct content


I can't put any direct content in my custom control, have a look:

    <Style TargetType="local:MyCustomControl">    
         <Setter Property="Template">           
            <Setter.Value>              
                <ControlTemplate TargetType="local:MyCustomControl">
                    <Grid>                  
                        <Viewport3D />                      
                        <!-- the viewport is working (proof provided) -->
                        <!-- both borders are needed -->

                        <Border>
                            <Border>                               
                                <ContentPresenter  />    
                            </Border>
                        </Border>                   
                    </Grid>             
                </ControlTemplate>              
            </Setter.Value>         
        </Setter>    
    </Style>

the class is derived from Control, in the static constructor DefaultStyleKeyProperty.OverrideMetadata is set.

When I try to use MyCustomControl:

    <local:MyCustomControl VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <TextBlock Margin="10,0,0,0" FontSize="16" Text="some test value" />
    </local:MyCustomControl>

this error message is shown:

Cannot add content to object of type MyCustomControl MyNamespace.MyCustomControl

What could be the problem? Is somthing wrong with the Contentpresenter?


Solution

  • Thanks ZerO, this was an excellent hint:

    MyCustomControl derived from Control - now it derives from ContenControl. After changing the base class I am now able to bind like suggested by ZerO.

    <ContentPresenter  Content="{TemplateBinding Content}"/>
    

    problem solved!