Wpf 为什么我需要键入ContentControl.Content而不仅仅是Content
我正在看一个关于数据模板的在线视频教程 演示代码如下所示Wpf 为什么我需要键入ContentControl.Content而不仅仅是Content,wpf,xaml,Wpf,Xaml,我正在看一个关于数据模板的在线视频教程 演示代码如下所示 <StackPanel.Resources> <ControlTemplate x:Key="MyButton"> <Grid> <Ellipse Fill="{TemplateBinding Background}" /> <ContentControl Content="
<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
。如果我们查看前面的代码行,它将显示椭圆填充=“{TemplateBinding Background}”
,而不是
为什么我们要声明
ContentControl
?是否因为按钮的属性Content
实际上是ContentControl
类型的对象,其中asBackground
只是按钮的字符串属性 如果您指定控制模板的类型(对于样式也相同),那么编译器将知道要查找内容属性的对象:
<ControlTemplate x:Key="MyButton" TargetType="{x:Type Button}">
<Grid>
<Ellipse Fill="{TemplateBinding Background}" />
<ContentControl Content="{TemplateBinding Content}" />
</Grid>
</ControlTemplate>
您可能还想阅读这里有关堆栈溢出的页面。在ControlTemplate
中添加TargetType=“{x:Type Button}”
否则模板不知道目标type@dkozl,我相信你,你在过去帮了我很多,所以我问这个问题不是粗鲁的,但为什么?事实上,它运行良好。这更多的是关于显式编码,还是在没有定义它的情况下会有gotcha?@dkozl,我测试了它-通过显式键入类型,我不需要ContentControl。。。我猜因为它知道类型,它知道它有什么属性。。。如果没有它,我想它只能访问对象(或控件或框架元素——无论它从何继承)。如果您想输入它,这很容易回答问题?基本上,如果您不指定TargetType
,就好像您将它指定给控件
类型,例如,它不定义内容
属性,因此您必须指定包含类型。有关更多信息,请查看例如,如果我输入目标类型作为基类(例如控件),那么我假设可以将其用于更多控件。例如,如果我的样式只更改了光标,那么它可以被继承自控件的所有控件共享?这是正确的吗?
<ControlTemplate x:Key="MyButton" TargetType="{x:Type ContentControl}">
<Grid>
<Ellipse Fill="{TemplateBinding Background}" />
<ContentControl Content="{TemplateBinding Content}" />
</Grid>
</ControlTemplate>
<RadioButton Template="{StaticResource MyButton}" Content="Hey" />
<ControlTemplate x:Key="MyButton" TargetType="{x:Type ContentControl}">
<Grid>
<Ellipse Fill="{TemplateBinding Background}" />
<ContentPresenter />
</Grid>
</ControlTemplate>