Style的x:Key属性,相当于在当前Window是资源中定义了一个名称为x:Key设定值的Style对象。如果没有设置x;Key,那么这个Style将对属于这个Window中所有CheckBox生效。首先设定的是Style的TargetType属性,它表示我们希望修改的目标类型。然后定义一个Setters的集合。每个Setter都表示修改的一个属性或者事件。Property设置属性名称,Value设置属性值。Event设置事件名称,Handler设置事件的响应函数名称。只要你在Resource做了类似的定义,在此Window中所使用的任何ChekcBox都会默认这些属性值。
<Window.Resources>
<Style TargetType="CheckBox">
<Setter Property="Height" Value="20"/>
<Setter Property="Width" Value="50"/>
<EventSetter Event="Checked" Handler="Checked_Click"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</Window.Resources>
我们只修改部分Element的属性值,而希望对某些特殊的Element做特殊处理。这样的需求WPF当然也是支持的。看看下面的代码:
<Style BasedOn="{StaticResource {x:Type CheckBox}}"
TargetType="CheckBox"
x:Key="WiderCheckBox">
<Setter Property="Width" Value="70"/>
</Style>
WPT通过BasedOn对这种特殊的Style提供了支持。很明显,BasedOn的意思是我们当前的Style基于在资源的CheckBox。这里又看到了x;Key扩展标记。因为我们需要的是一个特例,一个特殊的Style对象。为了以后引用这个Style,我们需要x:Key的标识作用。其它的代码与前面类似。
BaseOn属性是继承了前面定义的Style,如下面sample可以很好的理解BaseOn的含义
<Window x:Class="TreeViewSample.WindowTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TreeViewSample" Height="300" Width="300"
>
<Window.Resources>
<Style TargetType="{x:Type Button}" x:Key="styleBtn1">
<Setter Property="Background" Value="Red"/>
<Setter Property="Content" Value="Base"/>
</Style>
<Style BasedOn="{StaticResource styleBtn1}" TargetType="{x:Type Button}" x:Key="StyleBtn2">
<Setter Property="Background" Value="Green"/>
</Style>
</Window.Resources>
<Grid>
<StackPanel Orientation="Vertical">
<Button Style="{StaticResource StyleBtn2}" Name="SendBtn" Click="OnClick"></Button>
<Button Style="{StaticResource styleBtn1}" Name="ReceiveBtn" ></Button>
</StackPanel>
</Grid>
</Window>