WPF学习笔记(2)--样式(Style)

来源:互联网 发布:淘宝要求提供质检报告 编辑:程序博客网 时间:2024/05/19 03:28

在网上查了查WPF,看到了关于样式的文章,我试了一下,一起看看吧

在WPF中Style有3种使用方式:
一. Implicit Style(默认的样式)
      样式的作用范围为整个XAML文件,如果你没有为你的控件指定样式的话,系统将会使用默认的样式.
二. Named Style
      为控件指定特定的样式.
三. Derived Style
      样式的继承.

<Window x:Class="WindowsApplication3.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>

第一个Style对应Implicit Style(默认的样式),第二个Style对应Named Style(特定样式),每三个Style对应Derived 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>

 

他是说当鼠标在按钮上移动时,控件的前景色为红色,看在WPF中对外观的操作多方便,只要设置几个属性就行,要是在WinForm中,要写事件,才能实现控件这种效果,要是想多个控件都实现,那就必须封装一个控件了,看来还是WPF简单,学习,学习,学习。。。。

原创粉丝点击