WPF 自定义控件无法直接获取内容

Geo*_*uke 1 wpf custom-controls contentpresenter

我无法在自定义控件中放入任何直接内容,请看一下:

    <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>
Run Code Online (Sandbox Code Playgroud)

该类派生自Control,在静态构造函数中DefaultStyleKeyProperty.OverrideMetadata设置。

当我尝试使用 MyCustomControl 时:

    <local:MyCustomControl VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <TextBlock Margin="10,0,0,0" FontSize="16" Text="some test value" />
    </local:MyCustomControl>
Run Code Online (Sandbox Code Playgroud)

显示此错误消息:

无法将内容添加到 MyCustomControl MyNamespace.MyCustomControl 类型的对象

可能是什么问题呢?Contentpresenter 有问题吗?

Zer*_*er0 69

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

<ContentPresenter  Content="{TemplateBinding Content}"/>
Run Code Online (Sandbox Code Playgroud)