WPF ControlTemplates是否必须具有TargetType?
WPF中的ControlTemplates是否需要TargetType?我再造型某些控件,并注意comboboxitem,listiviewitem和ListBoxItem中都具有相同的模板:WPF ControlTemplates是否必须具有TargetType?
<ControlTemplate x:Key="ListBoxItemCT" TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd"
SnapsToDevicePixels="true"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
CornerRadius="1">
<ContentPresenter x:Name="cpItemContent"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
/>
</Border>
</ControlTemplate>
是否有可能只是删除的TargetType并拥有了所有三个一个模板?我试图做到这一点,但得到奇怪的错误和问题。我无法找到ControlTemplates必须具有的类型的任何特定参考。
对TargetType没有要求,但是如果你没有指定一个,它的行为将与你指定一个ControlType的TargetType相同。指定类型的主要优点是可以访问TemplateBindings和Triggers等类型的所有依赖属性,而无需使用所有者类型限定该属性。如果没有TargetType,您也可能会丢失隐式绑定,如ContentPresenter到ContentControl.Content属性。一旦确定了TargetType,模板只能应用于该类型的控件或从该类型派生。要在不同类型之间共享,只需指定一个公共基类 - ContentControl即可。
以下简单的模板将给出相同的基本结果,但首先是优选的,并且更常见的:
<ControlTemplate x:Key="CommonContentTemplate" TargetType="{x:Type ContentControl}">
<Border x:Name="Bd"
SnapsToDevicePixels="true"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
CornerRadius="1">
<ContentPresenter x:Name="cpItemContent"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</ControlTemplate>
没有类型的所有内容特性的需要手动有线了:
<ControlTemplate x:Key="CommonTemplate">
<Border x:Name="Bd"
SnapsToDevicePixels="true"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
CornerRadius="1">
<ContentPresenter x:Name="cpItemContent"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
ContentTemplateSelector="{TemplateBinding ContentControl.ContentTemplateSelector}"
ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"/>
</Border>
</ControlTemplate>
它们都来自System.Windows.Controls.ContentControl
,所以您可以改为定位。
谢谢!与上面相同的答案,但更简洁。 :) – dex3703 2010-09-03 15:28:43
谢谢!我花了最近两周制作这个大型的依赖属性图,所以这很有意义。我想我可以尝试... :) – dex3703 2010-09-03 15:28:17
这将解释我得到的奇怪的错误(关于找不到控制派生的东西),以及为什么内容不显示。 – dex3703 2010-09-03 15:31:17