There is no need for TargetType, but if you do not specify it, it will behave the same as if you specified TargetType Control. The main advantage is that specifying a type gives you access to all kinds of dependency properties in types such as TemplateBindings and Triggers, without having to qualify a property with an owner type. Without TargetType, you can also lose implicit bindings, such as ContentPresenter, to the ContentControl.Content property. As soon as you specify TargetType, this template can only be applied to controls of this type or derived from this type. For sharing between different types, just specify a common base class - ContentControl in this case.
The following simple templates will give the same basic result, but the first is preferable and more general:
<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>
Without a type, all content properties must be connected manually:
<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>
John bowen
source share