WPF DataTemplate属性设置为Content

Ing*_*als 4 wpf binding datatemplate templatebinding

WPF的新功能并且具有选项卡,并且在每个选项卡中,内容以弯曲的角落面板/窗口/ whateveryouwannacallit呈现.我不确定如何做到这一点(Style,ControlTemplate)但决定采用DataTemplate方式.

所以现在我有了这个DataTemplate:

<DataTemplate x:Key="TabContentPresenter" >
    <Border Margin="10"
            BorderBrush="{StaticResource DarkColorBrush}"
            CornerRadius="8"
            BorderThickness="2"
            Grid.Row="0"
            Padding="5" 
            Background="{TemplateBinding Background}">         

        <ContentPresenter Content="{Binding}" />

    </Border>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

正如你可以看到的背景属性,我不想在内容中设置背景颜色,但不知道如何.我在这里使用它.

<Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="120"/>
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <ContentControl ContentTemplate="{StaticResource TabContentPresenter}" Background="White">


                <!-- Something Here -->

            </ContentControl>

            <ContentControl ContentTemplate="{StaticResource TabContentPresenter}" Grid.Row="1" Background="Blue">

                <!-- Something Here -->

            </ContentControl>

        </Grid>
Run Code Online (Sandbox Code Playgroud)

在这里使用DataTemplate是错误还是有其他方法吗?

我可以直接在内容上设置背景,并从模板中的填充更改为内容中的边距,但在一些类似的情况下无法工作,只需设置一次就更好了.

编辑:

根据建议,我改为ControlTemplate并将其置于样式中.这解决了背景问题,但创造了一个更大的问题.现在内容不会出现.我在博客上看到,放一个targetType解决了这个问题,但它并没有解决我的问题.代码现在看起来像这样,并且还改变了ContentControl以使用样式而不是模板.

<Style x:Key="TabContentPresenter" TargetType="ContentControl" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ContentControl">
                <Border Margin="10"
            BorderBrush="{StaticResource DarkColorBrush}"
            CornerRadius="8"
            BorderThickness="2"
            Grid.Row="0"
            Background="{TemplateBinding Background}">

                    <ContentPresenter Content="{Binding}" />

                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)

Rag*_*han 7

使用ControlTemplate而不是DataTemplate

 <ControlTemplate  x:Key="TabContentPresenter">
        <Border Margin="10" 
                    CornerRadius="8" 
                    BorderThickness="2" 
                    Grid.Row="0" 
                    Padding="5"  
                    Background="{TemplateBinding Background}">
            <ContentPresenter Content="{Binding}"/>
        </Border>
    </ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

使用模板而不是ContentTemplate

<ContentControl  Background="Green" Template="{StaticResource  TabContentPresenter}"/>
Run Code Online (Sandbox Code Playgroud)

  • 最后弄清楚了,不得不将ContentPresenter Content属性更改为{TemplateBinding Content}. (2认同)

Ams*_*nna 5

可能是因为TemplateBinding无法使用DataTemplate.查看此问题了解详情.

即使它有效,您只需要一个ControlTemplate而不是datatemplate.