The Style property is defined by FrameworkElement so of course it’s inherited by Control and ButtonBase
and Button. Here’s a
program that defines a Style for Button in the Resources
section of the page:
Example 1. Project:
ButtonStyles File: MainPage.xaml (excerpt)
<phone:PhoneApplicationPage.Resources> <Style x:Key="btnStyle" TargetType="Button"> <Setter Property="Foreground" Value="SkyBlue" /> <Setter Property="FontSize" Value="36" /> <Setter Property="HorizontalAlignment" Value="Center" /> <Setter Property="Margin" Value="12" /> </Style> </phone:PhoneApplicationPage.Resources>
|
As usual, the Style
has an x:Key attribute and a TargetType. Three Button controls are arranged in a StackPanel.
Each has a reference to the Style
resource:
Example 2. Project:
ButtonStyles File: MainPage.xaml (excerpt)
<Grid x:Name=" ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel> <Button Content="Button No. 1" Style="{StaticResource btnStyle}" />
<Button Content="Button No. 2" Style="{StaticResource btnStyle}" />
<Button Content="Button No. 3" Style="{StaticResource btnStyle}" /> </StackPanel> </Grid>
|
Here’s what it looks like:
Now change one of those three Button objects to a ToggleButton:
<ToggleButton Content="Button No. 2"
Style="{StaticResource btnStyle}" />
This causes a runtime
error because you’re attempting to set a ToggleButton
from a Style whose TargetType is Button.
But if you look at the class
hierarchy, you’ll see that both Button
and ToggleButton derive from ButtonBase. Try setting that as the TargetType in the Style:
<Style x:Key="btnStyle" TargetType="ButtonBase">
<Setter Property="Foreground" Value="SkyBlue" />
<Setter Property="FontSize" Value="36" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="Margin" Value="12" />
</Style>
Now it works again. You can
even change the TargetType to Control, but that’s
about as far back as you can go with the particular example. If you
change the TargetType to FrameworkElement you’ll
get a runtime error because FrameworkElement
doesn’t have Foreground or FontSize properties.
As a general rule, it makes sense
to set TargetType
to be the most general class that has all the properties you’re defining
in the Style. You
can inherit from styles
based on derived classes. For example, you can begin with a Style with a TargetType
of ButtonBase and then have two derived styles for a TargetType of Button
and a TargetType of ToggleButton.