首页 > 解决方案 > 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?

标签: wpfcustom-controlscontentpresenter

解决方案


我认为您应该将您的内容绑定到您的演示者

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

推荐阅读