例如要使整个界面的TextBlock文字大小都为50与字体颜色都为黑色
方法一、在XAML的开头增加如下代码:
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize"
Value="50" />
<Setter Property="Foreground"
Value="Black" />
</Style>
</Window.Resources>
总体如下:
- 注意两处名称一致
这样界面中所有的TextBlock控件就都应用了相同的属性,
如果某一个需要其它属性,再在控件中直接指定相应的属性值就会替换资源中定义的了。
方法二、利用单一触发器(未指定具体的控件类型)
因未指定具体的控件类型,所以使用了Control,资源中定义key:
<Window.Resources>
<Style x:Key="smallbutton">
<Setter Property="Control.Foreground"
Value="blue" />
<Setter Property="Control.FontSize"
Value="20" />
<Setter Property="Control.FontFamily"
Value="Times new Roman" />
<Setter Property="Control.FontWeight"
Value="Bold" />
<Style.Triggers>
<!--这里使用了触发器,当鼠标移过控件的时候,控件的风格发生改变-->
<Trigger Property="Control.IsMouseOver"
Value="True">
<Setter Property="Control.Foreground"
Value="red" />
<Setter Property="Control.FontSize"
Value="24" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
控件中应用:
方法三、利用复合触发器(多条件,未指定具体的控件类型)
<Window.Resources>
<Style x:Key="smallbutton">
<Setter Property="Control.Foreground"
Value="blue" />
<Setter Property="Control.FontSize"
Value="20" />
<Style.Triggers>
<!--这里使用了单一触发器,当鼠标移过控件的时候,控件的风格发生改变-->
<Trigger Property="Control.IsMouseOver"
Value="True">
<Setter Property="Control.Foreground"
Value="red" />
</Trigger>
<!--定义复合条件触发器-->
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="Control.IsMouseOver"
Value="True" />
<!--通过Condition定义触发条件-->
<Condition Property="Button.IsPressed"
Value="True" />
<!--通过Condition定义触发条件-->
</MultiTrigger.Conditions>
<Setter Property="Control.Foreground"
Value="gray" />
<Setter Property="Control.FontStyle"
Value="Italic" />
</MultiTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
控件中应用:
方法四、使用风格样式(指定具体的控件类型)
比如:指定用于按钮的一种属性,如下,只有控件的style引用了此样式,才起作用。
<Window.Resources>
<Style TargetType="Button" x:Key="ButtonStyle">
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="FontFamily" Value="CourierNew"/>
</Style>
</Window.Resources>
使用样式:
<Button Width=" 100"
Grid.Row=" 1"
Height=" 30"
Style="{StaticResource ButtonStyle}
Click="Button_Click"/>
方法五、风格样式的相互继承
与类的继承原理相类似,我们可以使用BaseOn来使一个Style“继承”另一个Style
<Window.Resources>
<!--样式一-->
<Style TargetType="Button" x:Key="ButtonStyle">
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="FontFamily " Value="CourierNew"/>
</Style>
<!--样式二-->
<Style TargetType="Button" x:Key="TriggerButtonStyle" BasedOn="{StaticResource ButtonStyle}">
<Style.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
我们所声明的第二个Style,即TriggerButtonStyle,它“继承”于ButtonStyle,那么TriggerButtonStyle将会从ButtonStyle那里得到蓝色CourierNew文本的性质。
然后我们使用了Trigger来响应鼠标按下,
<Trigger Property="IsPressed" Value="True">表示当Button的IsPressed属性值变为True的时候,将做如下设置<Setter Property="Foreground" Value="Red"/>,即将Button的Foreground属性设置为Red。
这里有一个隐含的意思是:当当Button的IsPressed属性值变为False的时候,Foreground属性将恢复原值。