【发布时间】:2015-02-20 13:54:14
【问题描述】:
我正在观看有关 DataTemplates 的在线视频教程
演示代码如下
<StackPanel.Resources>
<ControlTemplate x:Key="MyButton">
<Grid>
<Ellipse Fill="{TemplateBinding Background}" />
<ContentControl Content="{TemplateBinding ContentControl.Content}" /><!--why this-->
</Grid>
</ControlTemplate>
</StackPanel.Resources>
<Button Content="Click me" Background="Green" Width="100" Height="50" Template="{StaticResource MyButton}" />
</StackPanel>
我迷路的地方是
<ContentControl Content="{TemplateBinding ContentControl.Content}" />
为什么是ControlControl.Content 而不仅仅是Content。如果我们在此之前查看代码行,它会显示 Ellipse Fill="{TemplateBinding Background}" 而不是 <Ellipse Fill="{TemplateBinding Ellipse.Background}" />
为什么我们声明ContentControl?是因为Button 的属性Content 实际上是ContentControl 类型的对象,而Background 只是Button 的字符串属性?
【问题讨论】:
-
in
ControlTemplate添加TargetType="{x:Type Button}"否则模板不知道目标类型 -
@dkozl,我相信你,你过去帮了我很多,所以我问这个问题并不粗鲁,但为什么呢?事实上,它运行良好。这更多是关于显式编码还是没有定义它的问题?
-
@dkozl,我测试了它——通过明确输入类型,我不需要 ContentControl...我猜是因为它知道类型,它知道它有什么属性...没有它,我猜它只能访问对象(或控件或框架元素 - 无论它继承自什么)。如果您想输入它,这很容易成为答案?
-
基本上,如果你不指定
TargetType,就像你会为Control类型指定它,但它没有定义Content属性,所以你必须指定包含类型。有关更多信息,请查看例如 here