学过css的朋友都熟悉样式这个术语 它和css样式很类似的规则,那么从基本开始讲解 首先看一下xaml代码

xaml代码

  <UserControl.Resources>
        <Style x:Key="btnstyle"  TargetType="Button">
            <Setter Property="Foreground" Value="Blue"> </Setter>
            <Setter Property="FontSize" Value="15"></Setter>
            <Setter Property="Cursor" Value="Hand"></Setter>
        </Style>
  </UserControl.Resources>

蓝色字段表示 元素类型的兼容 比如Button元素,红色字段表示 这个元素样式的属性

给一个Button应用

 <Button Content="Button" Style="{StaticResource btnstyle}" Height="23" 
HorizontalAlignment=
"Left" Margin="33,25,0,0" Name="button1" 
VerticalAlignment=
"Top" Width="75" />

 那么显示效果

如果去掉X;Key属性 它会自动给这个页面所有Button应用此样式 那么想某个元素去掉样式 给style属性写上[x;null}

  如果想继承这个样式 再附加一些样式的话 那么可以这样写

        <Style BasedOn="{StaticResource btnstyle}" TargetType="Button" x:Key="btnstyleB">
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                        <GradientStop Color="Red" Offset="0"></GradientStop>
                        <GradientStop Color="Yellow" Offset="1"></GradientStop>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Style>

  上面代码蓝色字段表示继承上一个样式 然后修改一下Button

<Button Content="Button" Style="{StaticResource btnstyleB}" Height="23" 
HorizontalAlignment=
"Left" Margin="33,25,0,0" Name="button1" 
VerticalAlignment=
"Top" Width="75" />

上面介绍是外部样式 接下来内部样式

<Button Content="Button"  Height="23" HorizontalAlignment="Left" Margin="33,25,0,0" Name="button1" VerticalAlignment="Top" Width="75" >
            <Button.Style>
                <Style   TargetType="Button">
                    <Setter Property="Foreground" Value="Blue"></Setter>
                    <Setter Property="FontSize" Value="15"></Setter>
                    <Setter Property="Cursor" Value="Hand"></Setter>
                    <Setter Property="Background">
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                                <GradientStop Color="Red" Offset="0"></GradientStop>
                                <GradientStop Color="Yellow" Offset="1"></GradientStop>
                            </LinearGradientBrush>
                        </Setter.Value>
                    </Setter>
                </Style>
            </Button.Style>
        </Button>

 

 button1.Style = (Style)this.Resources["btnstyleB"];

 

 

posted on 2012-06-24 21:31  gzh4455  阅读(117)  评论(0编辑  收藏  举报