Style

 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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值