WPF中的ControlTemplates需要TargetType吗?我正在重新设计一些控件的样式,并注意到comboboxitem、listiviewitem和listboxitem都有相同的模板:
<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必须有类型的任何特定引用。
发布于 2010-09-03 11:45:21
对TargetType没有要求,但如果不指定,它的行为将与指定TargetType的控制相同。
一旦指定了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>如果没有type,所有的内容属性都需要手动连接:
<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>发布于 2010-09-03 08:08:46
它们都是从System.Windows.Controls.ContentControl派生的,所以您可以将其作为目标。
发布于 2020-08-05 19:33:38
为了完整起见,请注意the documentation声明如下:
如果模板定义包含TargetType,则属性在ControlTemplate上是必需的。
尽管它没有解释这一需求,但很可能是John Bowen's answer给出的推理,即您必须手动指定Content等基本属性,否则这些属性将自动连接。
https://stackoverflow.com/questions/3632181
复制相似问题