Reputation: 152
I am a bit puzzled by the excessive verbosity of xaml in wpf. For e.g. when defining a control template, you still have to specify the target type as the control itself. Is specifying the TargetType necessary ? Since I am defining the template element of TargetControl does it not default to the TargetControl when not specified?
<local:TargetControl Width="100" Height="100">
<local:TargetControl.Template>
<ControlTemplate TargetType="local:TargetControl">
<Grid>
<Ellipse x:Name="PART_Target" Fill="Blue" />
<Grid>
</ControlTemplate>
</local:TargetControl.Template>
</local:TargetControl>
Upvotes: 2
Views: 141
Reputation: 35722
markup <ControlTemplate> </ControlTemplate>
means that new ControlTemplate instance is create using default constructor (new ControlTemplate()
). The constructor is not aware which element will use the template.
in this example
<ControlTemplate TargetType="local:TargetControl">
<Grid>
<Ellipse x:Name="PART_Target" Fill="Blue" />
<Grid>
</ControlTemplate>
template can be used without TargetType because it doesn't use any TargetControl
-specific properties for TemplateBinding
s. If TemplateBindings are required, TargetType also has to be set.
in most cases element template has the same TargetType as the type of element.
But there can be exeptional cases, e.g.: I want my RadioButtons and CheckBoxes look like colored circles - green when Checked and gray when Unchecked.
RadioButton and CheckBox derive from ToggleButton, so I create template for ToggleButton and apply to my RadioButtons and CheckBoxes:
<StackPanel>
<StackPanel.Resources>
<ControlTemplate TargetType="{x:Type ToggleButton}" x:Key="Toggle">
<Border Name="btn" BorderBrush="Black" Background="Gainsboro"
Width="28" Height="28" CornerRadius="14" />
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Background" TargetName="btn" Value="Lime" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</StackPanel.Resources>
<CheckBox Template="{StaticResource Toggle}" />
<RadioButton Template="{StaticResource Toggle}" />
<RadioButton Template="{StaticResource Toggle}" />
</StackPanel>
this example also demonstrates the situation when ControlTemplate is defined in resource dictionary without connection to specific element, so TargetType cannot be inferred.
so there are at least 3 cases when TargetType is not known for certain or not needed. So it is left to developers to always provide concrete type
Upvotes: 3