Why define a template inside a style in xaml, WPF?

I have been interested about this since I started using MS template templates as a basis for creating custom controls.

take an example shortcut, for example: http://msdn.microsoft.com/en-us/library/ms752327.aspx

why it is defined as follows:

<Style x:Key="{x:Type Label}" TargetType="Label"> <Setter Property="HorizontalContentAlignment" Value="Left" /> <Setter Property="VerticalContentAlignment" Value="Top" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Label"> <Border> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground"> <Setter.Value> <SolidColorBrush Color="{DynamicResource DisabledForegroundColor}" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> 

not like that:

 <ControlTemplate x:Key="{x:Type Label}" TargetType="Label"> <Border> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground"> <Setter.Value> <SolidColorBrush Color="{DynamicResource DisabledForegroundColor}" /> </Setter.Value> </Setter> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> 

and then called as a template directly, and not through a style property?

Is there a hidden reason why I don't see such things? or is it just one way to do something and what?

(NB: don’t tell me that this is due to the horizontal and vertical alignment setting! We all know that these are the default values ​​for the label, and it’s basically useless if you keep these values)

+6
templates styles wpf xaml
source share
1 answer

Without using a style, it is not possible to automatically assign a template to all instances of a particular control type. The x:Key="{x:Type Label}" setting for the control template does not automatically apply to this template for all elements of the Label type.

You can make the style applicable to all buttons under the declaration in the visualization tree by setting TargetType to Button , but you cannot do the same with a template unless you wrap it inside a Style that has a setter for the template.

Also note that in your example you can exchange

 <Style x:Key="{x:Type Label}" TargetType="Label"> 

FROM

 <Style TargetType="Label"> 

Because x:Key set to TargetType if the definition of x:Key omitted.

+8
source share

All Articles