当我们在 XAML 资源部分中定义 Style 并将其 TargetType 属性设置为特定控件类型时,我们不需要将 Style 属性设置为该类型的控件。例如
<Window.Resources>
<Style TargetType="Button">
<Setter Property="Content" Value="Style set for all buttons"/>
<Setter Property="Background" Value="Gray"/>
</Style>
</Window.Resources>
<Grid>
<Button Height="27" HorizontalAlignment="Left" Margin="119,56,0,0" Name="button1" VerticalAlignment="Top" Width="140" />
<Button Style="{x:Null}" Content="No Style" Height="27" HorizontalAlignment="Left" Margin="212,121,0,0" Name="button2" VerticalAlignment="Top" Width="141" />
<Button Content="Button" Height="25" HorizontalAlignment="Left" Margin="296,183,0,0" Name="button3" VerticalAlignment="Top" Width="158" />
</Grid>
但是当我们想为窗口中的所有控件定义样式时,我们需要为每个控件添加 Style 属性以具有该定义的样式。例如
<Window.Resources>
<Style x:Key="Style1" TargetType="Control">
<Setter Property="Control.Background" Value="Gray"/>
</Style>
</Window.Resources>
<Grid>
<Button Style="{StaticResource Style1}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="67,52,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
<Label Style="{StaticResource Style1}" Content="Label" Height="27" HorizontalAlignment="Left" Margin="189,99,0,0" Name="label1" VerticalAlignment="Top" Width="83" />
</Grid>
我们不能在上面的示例中使用按钮和标签访问样式“Style1”,而无需在按钮和标签控件中专门设置样式属性吗?
提前致谢。