CheckBox自定义样式的例子

代码

App.xaml

  1. <Style x:Key="SlidingBlock" TargetType="{x:Type CheckBox}">
  2. <Setter Property="Foreground" Value="White" />
  3. <Setter Property="Padding" Value="2" />
  4. <Setter Property="Template">
  5. <Setter.Value>
  6. <ControlTemplate TargetType="{x:Type CheckBox}">
  7. <Border
  8. Width="Auto"
  9. Height="Auto"
  10. Margin="0"
  11. BorderBrush="Black"
  12. BorderThickness="1"
  13. CornerRadius="2">
  14. <StackPanel Orientation="Horizontal">
  15. <Border
  16. x:Name="PART_UPC"
  17. Width="Auto"
  18. Height="Auto"
  19. Margin="1.3"
  20. Padding="5,2"
  21. CornerRadius="2">
  22. <TextBlock
  23. HorizontalAlignment="Center"
  24. VerticalAlignment="Center"
  25. FontSize="12"
  26. Text="Left" />
  27. </Border>
  28. <Border
  29. x:Name="PART_DWC"
  30. Width="Auto"
  31. Height="Auto"
  32. Margin="1.3"
  33. Padding="5,2"
  34. CornerRadius="2">
  35. <TextBlock
  36. HorizontalAlignment="Center"
  37. VerticalAlignment="Center"
  38. FontSize="12"
  39. Text="Right" />
  40. </Border>
  41. </StackPanel>
  42. </Border>
  43. <ControlTemplate.Triggers>
  44. <Trigger Property="IsChecked" Value="True">
  45. <Setter TargetName="PART_UPC" Property="Background" Value="#997CFC00" />
  46. </Trigger>
  47. <Trigger Property="IsChecked" Value="False">
  48. <Setter TargetName="PART_DWC" Property="Background" Value="#997CFC00" />
  49. </Trigger>
  50. </ControlTemplate.Triggers>
  51. </ControlTemplate>
  52. </Setter.Value>
  53. </Setter>
  54. </Style>

CheckBoxStyleSample.xaml

  1. <CheckBox
  2. Width="80"
  3. HorizontalAlignment="Center"
  4. VerticalAlignment="Center"
  5. Foreground="Black"
  6. Style="{StaticResource SlidingBlock}" />

效果

checkbox sample.gif