34

ContentControl.Template 和 ContentControl.ContentTemplate 有什么区别?我什么时候用哪个?

例如,我可以在 WPF 的 xaml 文件中编写:

<ContentControl>
    <ContentControl.Template>
        <ControlTemplate>
            <Label Content="This is from the Template"/>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

注意 ContentControl。模板标签

或者我可以这样写:

<ContentControl>
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Label Content="This is From the ContentTemplate"/>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

注意 ContentControl。内容模板标签

输出看起来相同,在第一种情况下,我使用 ControlTemplate,在另一种情况下使用 DataTemplate。但是,我应该如何决定是否必须使用 .Template 或 .ContentTemplate?以及这有什么影响(例如对 DataBinding、Property Inheritance,...)。

4

1 回答 1

25

Template属性定义了控件本身的外观,而ContentTemplate定义了控件区域的模板Content。来自 MSDN 的有趣点:

如果控件没有 ControlTemplate,则控件将不会出现在您的应用程序中。

当我们查看这两个属性的数据类型时,这一点变得更加清楚:

于 2011-09-27T10:45:07.933 回答