基础用法

  1. <Window.Resources>
  2. <Style x:Key="btnStyle" TargetType="{x:Type Button}">
  3. <Setter Property="Height" Value="40"/>
  4. <Setter Property="Width" Value="100"/>
  5. <Setter Property="Background" Value="Beige"/>
  6. <Setter Property="RenderTransform">
  7. <Setter.Value>
  8. <RotateTransform Angle="45"/>
  9. </Setter.Value>
  10. </Setter>
  11. </Style>
  12. </Window.Resources>
  13. <StackPanel>
  14. <Button Content="btn1" Style="{StaticResource ResourceKey=btnStyle}"/>
  15. <Button Content="btn2" Style="{StaticResource ResourceKey=btnStyle}"/>
  16. </StackPanel>

样式的继承机制BasedOn=”{StaticResource keyName}”

ResourceKey=可以省略,当有键名时,如果没有键名,则需要默认为TargetType值{StaticResource {x:Type Control}}

  1. <Window.Resources>
  2. <Style x:Key="controlStyle" TargetType="{x:Type Control}">
  3. <Setter Property="Height" Value="40"/>
  4. <Setter Property="Width" Value="100"/>
  5. <Setter Property="Background" Value="Blue"/>
  6. <Setter Property="RenderTransform">
  7. <Setter.Value>
  8. <RotateTransform Angle="45"/>
  9. </Setter.Value>
  10. </Setter>
  11. </Style>
  12. <Style x:Key="btnStyle" BasedOn="{StaticResource ResourceKey=controlStyle}"
  13. TargetType="{x:Type Button}">
  14. <Setter Property="Background" Value="Gray"/>
  15. </Style>
  16. <Style x:Key="radioBtn" BasedOn="{StaticResource controlStyle}"
  17. TargetType="{x:Type RadioButton}">
  18. <Setter Property="FontSize" Value="50"/>
  19. </Style>
  20. </Window.Resources>
  21. <StackPanel>
  22. <Button Content="btn1" Style="{StaticResource ResourceKey=btnStyle}"/>
  23. <Button Content="btn2" Style="{StaticResource ResourceKey=btnStyle}"/>
  24. <RadioButton Content="radioBtn" Style="{StaticResource radioBtn}"/>
  25. </StackPanel>

触发器

三种触发器:
(1)属性触发器(Trigger):如代码1所示
(2)数据触发器(DataTrigger):普通.NET属性,而不仅仅依赖属性值改变时触发
(3)事件触发器(EventTrigger):触发路由事件时会被调用,代码2所示

  1. <Style x:Key="btnStyle" BasedOn="{StaticResource ResourceKey=controlStyle}"
  2. TargetType="{x:Type Button}">
  3. <Setter Property="Background" Value="Gray"/>
  4. <Style.Triggers>
  5. <Trigger Property="IsMouseOver" Value="True">
  6. <Setter Property="Background" Value="BlanchedAlmond">
  7. </Setter>
  8. </Trigger>
  9. </Style.Triggers>
  10. </Style>
  1. <Button Content="btn1" Style="{StaticResource ResourceKey=btnStyle}">
  2. <Button.Triggers>
  3. <EventTrigger RoutedEvent="Button.Loaded">
  4. <BeginStoryboard>
  5. <Storyboard>
  6. <DoubleAnimation Storyboard.TargetProperty="Opacity" From="0"
  7. To="1" Duration="0:0:5"/>
  8. </Storyboard>
  9. </BeginStoryboard>
  10. </EventTrigger>
  11. </Button.Triggers>
  12. </Button>