WPF DataTemplate属性设置为内容

5

如果您是WPF新手,需要在选项卡中显示内容,并且每个选项卡中的内容以弯曲角面板/窗口/任何您想称之为的方式呈现。我不确定如何实现这一点(样式、控件模板),但决定采用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>

正如您可以看到的那样,通过使用background属性,我想设置内容的背景颜色,但我不知道该怎么做。在这里我使用它。

<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>

在这里使用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>
2个回答

9

使用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>

使用Template而不是ContentTemplate

<ContentControl  Background="Green" Template="{StaticResource  TabContentPresenter}"/>

这在背景上工作了,但是现在我的内容不显示在边框内。 - Ingó Vals
2
终于搞定了,不得不将ContentPresenter的Content属性更改为{TemplateBinding Content}。 - Ingó Vals

5

可能是因为TemplateBinding与DataTemplate不兼容。详情请查看此问题

即使它可以工作,你只需要一个ControlTemplate而不是一个DataTemplate。


谢谢,我确实知道TemplateBinding不起作用,我把它放在那里只是为了展示我想要的效果。我不太清楚DataTemplate和ControlTemplate之间的区别,所以我从来不知道该使用哪一个。 - Ingó Vals
第一个链接已经失效。 - Deantwo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接