WPF 写一个checkbox样式
时间: 2024-09-21 19:02:40 浏览: 33
WPF 自定义CheckBox样式
在Windows Presentation Foundation (WPF)中,你可以自定义Checkbox的样式来改变其外观。下面是一个简单的例子,展示了如何创建一个自定义的Checkbox样式:
```xml
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{DynamicResource TextColorBrush}" />
<Setter Property="Background" Value="#F0F0F0" />
<Setter Property="BorderBrush" Value="{DynamicResource BorderColorBrush}"/>
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<Grid Background="{TemplateBinding Background}">
<Viewbox>
<Path Data="M 0,0 L 8,4 L 4,8 Z" Fill="{TemplateBinding Foreground}"
Stretch="UniformToFill" Stroke="{TemplateBinding BorderBrush}"
StrokeThickness="{TemplateBinding BorderThickness}" Margin="4" />
</Viewbox>
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Data">
<Setter.Value>
M 4,0 L 0,4 L 8,4 L 4,8 Z
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="{DynamicResource HoverColorBrush}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- 这些ColorBrush资源需要在App.xaml或某个ResourceDictionary中定义 -->
<ResourceDictionary>
<SolidColorBrush x:Key="TextColorBrush" Color="Black"/>
<SolidColorBrush x:Key="BorderColorBrush" Color="Gray"/>
<SolidColorBrush x:Key="HoverColorBrush" Color="LightGray"/>
</ResourceDictionary>
```
这个样式将Checkbox的背景设置为淡灰色,勾选状态下的图形也相应改变,并添加了鼠标悬停时边框颜色的变化。`TextColorBrush`、`BorderColorBrush`和`HoverColorBrush`是需要在应用程序资源文件中定义的颜色刷。
阅读全文