It's not uncommon for me to write something like below for styling a data entry form, but my problem is that TextBox
and TextBlock
don't seem to implement the Setters that are in the BaseElementStyle
. Usually I need to define them separately.
Why is this? And is there a way around it?
I am guessing it has to do with the fact they are usually used in other control templates (for example TextBlock is used in most controls and TextBox is used in DatePickers and ComboBoxes)
<Style x:Key="BaseElementStyle" TargetType="{x:Type FrameworkElement}">
<Setter Property="Margin" Value="5" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource BaseElementStyle}" />
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource BaseElementStyle}" />
<Style TargetType="{x:Type Label}" BasedOn="{StaticResource BaseElementStyle}" />
<Style TargetType="{x:Type ComboBox}" BasedOn="{StaticResource BaseElementStyle}" />
<Style TargetType="{x:Type DatePicker}" BasedOn="{StaticResource BaseElementStyle}" />
<Style TargetType="{x:Type CheckBox}" BasedOn="{StaticResource BaseElementStyle}" />
Also keep in mind that WPF considers a
ControlTemplate
to be an inflation boundary and does NOT apply default styles inside of templates. The exception to the rule: anything that inherits fromControl
WILL BE inflated with the default style. SinceTextBlock
inherits fromFrameworkElement
and not from Control, if you use of it inside of aControlTemplate
you will also have to apply it's style manually. This is true for both TextBlocks that are added by hand, or by TextBlocks added by WPF for stringContent
. A quick example:For more information, see this blog post:
http://blogs.msdn.com/b/wpfsdk/archive/2009/08/27/implicit-styles-templates-controls-and-frameworkelements.aspx
I would like to suggest the two possible workarounds. It seems that each of Key and Type can be used but both of them cannot be used together as your question case,
x:Key="BaseElementStyle" TargetType="{x:Type FrameworkElement}"
.using x:Key
using x:Type