作为WPF中的一个重要的内容, 他允许用户创建动态的用户界面.可以有效的将业务逻辑与UI表现进行分离.
在WPF中Style有3种使用方式:
一. Implicit Style(默认的样式)
样式的作用范围为整个XAML文件,如果你没有为你的控件指定样式的话,系统将会使用默认的样式.
二. Named Style
为控件指定特定的样式.
三. Derived Style
样式的继承.
下面的例子清楚的说明了此三种样式的使用形式:
<
Window
x:Class
="Style.Window1"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
Title
="Style"
Height
="300"
Width
="300"
>
<
Window
.Resources
>
<
Style
TargetType
="{x:Type Button}"
>
<
Setter
Property
="Control.Background"
Value
="red"
/>
</
Style
>
<
Style
TargetType
="{x:Type Button}"
x:Key
="BlueButton"
>
<
Setter
Property
="Control.Background"
Value
="blue"
/>
</
Style
>
<
Style
TargetType
="{x:Type Button}"
x:Key
="YellowFont"
BasedOn
="{StaticResource BlueButton}"
>
<
Setter
Property
="Control.Foreground"
Value
="Yellow"
/>
<
Style
.Triggers
>
<
Trigger
Property
="Button.IsMouseOver"
Value
="True"
>
<
Setter
Property
="Control.Foreground"
Value
="Red"
/>
</
Trigger
>
</
Style.Triggers
>
</
Style
>
</
Window.Resources
>
<
Grid
>
<
Button
Name
="Button1"
Margin
="73,0,119,71"
Height
="25"
VerticalAlignment
="Bottom"
>
Button1
</
Button
>
<
Button
Name
="Button2"
Style
="{StaticResource BlueButton}"
Height
="25"
Margin
="85,60,107,0"
VerticalAlignment
="Top"
>
Button2
</
Button
>
<
Button
Name
="Button3"
Style
="{StaticResource YellowFont}"
Margin
="146,120,46,122"
>
Button3
</
Button
>
</
Grid
>
</
Window
>
Trigger
用数据库中的术语来说就是触发器.使用此功能可以实现根据不同的事件(如:鼠标经过)来改变控件的样式.
<
Style
.Triggers
>
<
Trigger
Property
="Button.IsMouseOver"
Value
="True"
>
<
Setter
Property
="Control.Foreground"
Value
="Red"
/>
</
Trigger
>
</
Style.Triggers
>
上面的例子中使用到了几个XAML的特殊标记:
TargetType = “{x:Type Button}”
x:Type: 用于指定使用的类型,后面跟的是一个类的名字.此标记主要用于Style中.
x:Key :指定一个唯一的表示名称,此名称用于资源的引用.
Style="{StaticResource BlueButton}"
StaticResource : 用于标记引用的资源已经被定义.与之相对应的是DynamicResource
Property :使用的是Dependency Property 属性名称
原文地址:http://www.cnblogs.com/czhenq/archive/2006/11/27/574423.html