这一章依上一章内容,进一步讲解如果通过样式对统一控件类进行外观设置。
Stye关键字是WPF提供对控件类样式设置的接口。它可以应用于应用程序的每一个控件,其通常定义在ResourceDictionary(如FrameworkElement的Resources)中以AXML形式定义。
继上一章例程里,我们的FrameworkElement框架为Window,所以我们可以将其定义在Window.Resources下:
<Window.Resources> <Style TargetType="Button"> <Setter Property="FontSize" Value="14"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5" Opacity="0.2"> <GradientStop Color="Green" Offset="0.0"/> <GradientStop Color="White" Offset=" 0.5"/> </LinearGradientBrush> </Setter.Value> </Setter> </Style> </Window.Resources>
完整代码:
<Window x:Class="WpfControls.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="Button"> <Setter Property="FontSize" Value="14"/> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5" Opacity="0.2"> <GradientStop Color="Green" Offset="0.0"/> <GradientStop Color="White" Offset=" 0.5"/> </LinearGradientBrush> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <Grid.Background> <LinearGradientBrush StartPoint="0,1.5" EndPoint="0.5,0.1" Opacity="0.2"> <LinearGradientBrush.GradientStops> <GradientStop Color="Green" Offset="0.0"/> <GradientStop Color="LightBlue" Offset="0.75"/> <GradientStop Color="LightCoral" Offset="1.2"/> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Grid.Background> <Grid.RowDefinitions> <RowDefinition Height="30"/> <RowDefinition Height="30"/> <RowDefinition Height="30"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Label Grid.Column="0" FontSize="14" FontWeight="Bold">Entry your First Name:</Label> <TextBox Grid.Row="0" Grid.Column="1" Name="firstName" Margin="0,5,10,5"/> <Label Grid.Row="1">Entry your Last Name:</Label> <TextBox Grid.Column="1" Grid.Row="1" Name="lastName" Margin="0,5,10,5"/> <Button Grid.Row="2" Grid.Column="0" Name="submit" Margin="2">View message</Button> <Button Grid.Row="2" Grid.Column="2" Name="Clear" Margin="2">Clear Name</Button> </Grid> </Window>
编译运行效果:
利用Style关键字我们可以定义样式,一次性为多个控件设置属性,但有时候,有些用户总喜欢一些奇形怪状的控件才能满足他们的内心的变态需求,那么作为程序猿,为了满足这些客户的需要也是有办法解决的,我们将在下一章讲解程序猿应该怎么满足这些客户的要求。
End.
谢谢.